babylon.max.js 3.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. return Color3;
  211. }());
  212. BABYLON.Color3 = Color3;
  213. var Color4 = (function () {
  214. function Color4(r, g, b, a) {
  215. this.r = r;
  216. this.g = g;
  217. this.b = b;
  218. this.a = a;
  219. }
  220. // Operators
  221. Color4.prototype.addInPlace = function (right) {
  222. this.r += right.r;
  223. this.g += right.g;
  224. this.b += right.b;
  225. this.a += right.a;
  226. return this;
  227. };
  228. Color4.prototype.asArray = function () {
  229. var result = [];
  230. this.toArray(result, 0);
  231. return result;
  232. };
  233. Color4.prototype.toArray = function (array, index) {
  234. if (index === undefined) {
  235. index = 0;
  236. }
  237. array[index] = this.r;
  238. array[index + 1] = this.g;
  239. array[index + 2] = this.b;
  240. array[index + 3] = this.a;
  241. return this;
  242. };
  243. Color4.prototype.add = function (right) {
  244. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  245. };
  246. Color4.prototype.subtract = function (right) {
  247. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  248. };
  249. Color4.prototype.subtractToRef = function (right, result) {
  250. result.r = this.r - right.r;
  251. result.g = this.g - right.g;
  252. result.b = this.b - right.b;
  253. result.a = this.a - right.a;
  254. return this;
  255. };
  256. Color4.prototype.scale = function (scale) {
  257. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  258. };
  259. Color4.prototype.scaleToRef = function (scale, result) {
  260. result.r = this.r * scale;
  261. result.g = this.g * scale;
  262. result.b = this.b * scale;
  263. result.a = this.a * scale;
  264. return this;
  265. };
  266. /**
  267. * Multipy an RGBA Color4 value by another and return a new Color4 object
  268. * @param color The Color4 (RGBA) value to multiply by
  269. * @returns A new Color4.
  270. */
  271. Color4.prototype.multiply = function (color) {
  272. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  273. };
  274. /**
  275. * Multipy an RGBA Color4 value by another and push the result in a reference value
  276. * @param color The Color4 (RGBA) value to multiply by
  277. * @param result The Color4 (RGBA) to fill the result in
  278. * @returns the result Color4.
  279. */
  280. Color4.prototype.multiplyToRef = function (color, result) {
  281. result.r = this.r * color.r;
  282. result.g = this.g * color.g;
  283. result.b = this.b * color.b;
  284. result.a = this.a * color.a;
  285. return result;
  286. };
  287. Color4.prototype.toString = function () {
  288. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  289. };
  290. Color4.prototype.getClassName = function () {
  291. return "Color4";
  292. };
  293. Color4.prototype.getHashCode = function () {
  294. var hash = this.r || 0;
  295. hash = (hash * 397) ^ (this.g || 0);
  296. hash = (hash * 397) ^ (this.b || 0);
  297. hash = (hash * 397) ^ (this.a || 0);
  298. return hash;
  299. };
  300. Color4.prototype.clone = function () {
  301. return new Color4(this.r, this.g, this.b, this.a);
  302. };
  303. Color4.prototype.copyFrom = function (source) {
  304. this.r = source.r;
  305. this.g = source.g;
  306. this.b = source.b;
  307. this.a = source.a;
  308. return this;
  309. };
  310. Color4.prototype.toHexString = function () {
  311. var intR = (this.r * 255) | 0;
  312. var intG = (this.g * 255) | 0;
  313. var intB = (this.b * 255) | 0;
  314. var intA = (this.a * 255) | 0;
  315. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  316. };
  317. // Statics
  318. Color4.FromHexString = function (hex) {
  319. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  320. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  321. return new Color4(0, 0, 0, 0);
  322. }
  323. var r = parseInt(hex.substring(1, 3), 16);
  324. var g = parseInt(hex.substring(3, 5), 16);
  325. var b = parseInt(hex.substring(5, 7), 16);
  326. var a = parseInt(hex.substring(7, 9), 16);
  327. return Color4.FromInts(r, g, b, a);
  328. };
  329. Color4.Lerp = function (left, right, amount) {
  330. var result = new Color4(0, 0, 0, 0);
  331. Color4.LerpToRef(left, right, amount, result);
  332. return result;
  333. };
  334. Color4.LerpToRef = function (left, right, amount, result) {
  335. result.r = left.r + (right.r - left.r) * amount;
  336. result.g = left.g + (right.g - left.g) * amount;
  337. result.b = left.b + (right.b - left.b) * amount;
  338. result.a = left.a + (right.a - left.a) * amount;
  339. };
  340. Color4.FromArray = function (array, offset) {
  341. if (offset === void 0) { offset = 0; }
  342. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  343. };
  344. Color4.FromInts = function (r, g, b, a) {
  345. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  346. };
  347. Color4.CheckColors4 = function (colors, count) {
  348. // Check if color3 was used
  349. if (colors.length === count * 3) {
  350. var colors4 = [];
  351. for (var index = 0; index < colors.length; index += 3) {
  352. var newIndex = (index / 3) * 4;
  353. colors4[newIndex] = colors[index];
  354. colors4[newIndex + 1] = colors[index + 1];
  355. colors4[newIndex + 2] = colors[index + 2];
  356. colors4[newIndex + 3] = 1.0;
  357. }
  358. return colors4;
  359. }
  360. return colors;
  361. };
  362. return Color4;
  363. }());
  364. BABYLON.Color4 = Color4;
  365. var Vector2 = (function () {
  366. function Vector2(x, y) {
  367. this.x = x;
  368. this.y = y;
  369. }
  370. Vector2.prototype.toString = function () {
  371. return "{X: " + this.x + " Y:" + this.y + "}";
  372. };
  373. Vector2.prototype.getClassName = function () {
  374. return "Vector2";
  375. };
  376. Vector2.prototype.getHashCode = function () {
  377. var hash = this.x || 0;
  378. hash = (hash * 397) ^ (this.y || 0);
  379. return hash;
  380. };
  381. // Operators
  382. Vector2.prototype.toArray = function (array, index) {
  383. if (index === void 0) { index = 0; }
  384. array[index] = this.x;
  385. array[index + 1] = this.y;
  386. return this;
  387. };
  388. Vector2.prototype.asArray = function () {
  389. var result = [];
  390. this.toArray(result, 0);
  391. return result;
  392. };
  393. Vector2.prototype.copyFrom = function (source) {
  394. this.x = source.x;
  395. this.y = source.y;
  396. return this;
  397. };
  398. Vector2.prototype.copyFromFloats = function (x, y) {
  399. this.x = x;
  400. this.y = y;
  401. return this;
  402. };
  403. Vector2.prototype.add = function (otherVector) {
  404. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  405. };
  406. Vector2.prototype.addToRef = function (otherVector, result) {
  407. result.x = this.x + otherVector.x;
  408. result.y = this.y + otherVector.y;
  409. return this;
  410. };
  411. Vector2.prototype.addInPlace = function (otherVector) {
  412. this.x += otherVector.x;
  413. this.y += otherVector.y;
  414. return this;
  415. };
  416. Vector2.prototype.addVector3 = function (otherVector) {
  417. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  418. };
  419. Vector2.prototype.subtract = function (otherVector) {
  420. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  421. };
  422. Vector2.prototype.subtractToRef = function (otherVector, result) {
  423. result.x = this.x - otherVector.x;
  424. result.y = this.y - otherVector.y;
  425. return this;
  426. };
  427. Vector2.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. return this;
  431. };
  432. Vector2.prototype.multiplyInPlace = function (otherVector) {
  433. this.x *= otherVector.x;
  434. this.y *= otherVector.y;
  435. return this;
  436. };
  437. Vector2.prototype.multiply = function (otherVector) {
  438. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  439. };
  440. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  441. result.x = this.x * otherVector.x;
  442. result.y = this.y * otherVector.y;
  443. return this;
  444. };
  445. Vector2.prototype.multiplyByFloats = function (x, y) {
  446. return new Vector2(this.x * x, this.y * y);
  447. };
  448. Vector2.prototype.divide = function (otherVector) {
  449. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  450. };
  451. Vector2.prototype.divideToRef = function (otherVector, result) {
  452. result.x = this.x / otherVector.x;
  453. result.y = this.y / otherVector.y;
  454. return this;
  455. };
  456. Vector2.prototype.negate = function () {
  457. return new Vector2(-this.x, -this.y);
  458. };
  459. Vector2.prototype.scaleInPlace = function (scale) {
  460. this.x *= scale;
  461. this.y *= scale;
  462. return this;
  463. };
  464. Vector2.prototype.scale = function (scale) {
  465. return new Vector2(this.x * scale, this.y * scale);
  466. };
  467. Vector2.prototype.equals = function (otherVector) {
  468. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  469. };
  470. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  471. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  472. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  473. };
  474. // Properties
  475. Vector2.prototype.length = function () {
  476. return Math.sqrt(this.x * this.x + this.y * this.y);
  477. };
  478. Vector2.prototype.lengthSquared = function () {
  479. return (this.x * this.x + this.y * this.y);
  480. };
  481. // Methods
  482. Vector2.prototype.normalize = function () {
  483. var len = this.length();
  484. if (len === 0)
  485. return this;
  486. var num = 1.0 / len;
  487. this.x *= num;
  488. this.y *= num;
  489. return this;
  490. };
  491. Vector2.prototype.clone = function () {
  492. return new Vector2(this.x, this.y);
  493. };
  494. // Statics
  495. Vector2.Zero = function () {
  496. return new Vector2(0, 0);
  497. };
  498. Vector2.FromArray = function (array, offset) {
  499. if (offset === void 0) { offset = 0; }
  500. return new Vector2(array[offset], array[offset + 1]);
  501. };
  502. Vector2.FromArrayToRef = function (array, offset, result) {
  503. result.x = array[offset];
  504. result.y = array[offset + 1];
  505. };
  506. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  507. var squared = amount * amount;
  508. var cubed = amount * squared;
  509. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  510. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  511. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  512. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  513. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  514. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  515. return new Vector2(x, y);
  516. };
  517. Vector2.Clamp = function (value, min, max) {
  518. var x = value.x;
  519. x = (x > max.x) ? max.x : x;
  520. x = (x < min.x) ? min.x : x;
  521. var y = value.y;
  522. y = (y > max.y) ? max.y : y;
  523. y = (y < min.y) ? min.y : y;
  524. return new Vector2(x, y);
  525. };
  526. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  527. var squared = amount * amount;
  528. var cubed = amount * squared;
  529. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  530. var part2 = (-2.0 * cubed) + (3.0 * squared);
  531. var part3 = (cubed - (2.0 * squared)) + amount;
  532. var part4 = cubed - squared;
  533. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  534. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  535. return new Vector2(x, y);
  536. };
  537. Vector2.Lerp = function (start, end, amount) {
  538. var x = start.x + ((end.x - start.x) * amount);
  539. var y = start.y + ((end.y - start.y) * amount);
  540. return new Vector2(x, y);
  541. };
  542. Vector2.Dot = function (left, right) {
  543. return left.x * right.x + left.y * right.y;
  544. };
  545. Vector2.Normalize = function (vector) {
  546. var newVector = vector.clone();
  547. newVector.normalize();
  548. return newVector;
  549. };
  550. Vector2.Minimize = function (left, right) {
  551. var x = (left.x < right.x) ? left.x : right.x;
  552. var y = (left.y < right.y) ? left.y : right.y;
  553. return new Vector2(x, y);
  554. };
  555. Vector2.Maximize = function (left, right) {
  556. var x = (left.x > right.x) ? left.x : right.x;
  557. var y = (left.y > right.y) ? left.y : right.y;
  558. return new Vector2(x, y);
  559. };
  560. Vector2.Transform = function (vector, transformation) {
  561. var r = Vector2.Zero();
  562. Vector2.TransformToRef(vector, transformation, r);
  563. return r;
  564. };
  565. Vector2.TransformToRef = function (vector, transformation, result) {
  566. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  567. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  568. result.x = x;
  569. result.y = y;
  570. };
  571. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  572. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  573. var sign = a < 0 ? -1 : 1;
  574. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  575. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  576. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  577. };
  578. Vector2.Distance = function (value1, value2) {
  579. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  580. };
  581. Vector2.DistanceSquared = function (value1, value2) {
  582. var x = value1.x - value2.x;
  583. var y = value1.y - value2.y;
  584. return (x * x) + (y * y);
  585. };
  586. Vector2.Center = function (value1, value2) {
  587. var center = value1.add(value2);
  588. center.scaleInPlace(0.5);
  589. return center;
  590. };
  591. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  592. var l2 = Vector2.DistanceSquared(segA, segB);
  593. if (l2 === 0.0) {
  594. return Vector2.Distance(p, segA);
  595. }
  596. var v = segB.subtract(segA);
  597. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  598. var proj = segA.add(v.multiplyByFloats(t, t));
  599. return Vector2.Distance(p, proj);
  600. };
  601. return Vector2;
  602. }());
  603. BABYLON.Vector2 = Vector2;
  604. var Vector3 = (function () {
  605. function Vector3(x, y, z) {
  606. this.x = x;
  607. this.y = y;
  608. this.z = z;
  609. }
  610. Vector3.prototype.toString = function () {
  611. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  612. };
  613. Vector3.prototype.getClassName = function () {
  614. return "Vector3";
  615. };
  616. Vector3.prototype.getHashCode = function () {
  617. var hash = this.x || 0;
  618. hash = (hash * 397) ^ (this.y || 0);
  619. hash = (hash * 397) ^ (this.z || 0);
  620. return hash;
  621. };
  622. // Operators
  623. Vector3.prototype.asArray = function () {
  624. var result = [];
  625. this.toArray(result, 0);
  626. return result;
  627. };
  628. Vector3.prototype.toArray = function (array, index) {
  629. if (index === void 0) { index = 0; }
  630. array[index] = this.x;
  631. array[index + 1] = this.y;
  632. array[index + 2] = this.z;
  633. return this;
  634. };
  635. Vector3.prototype.toQuaternion = function () {
  636. var result = new Quaternion(0, 0, 0, 1);
  637. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  638. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  639. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  640. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  641. var cosy = Math.cos(this.y * 0.5);
  642. var siny = Math.sin(this.y * 0.5);
  643. result.x = coszMinusx * siny;
  644. result.y = -sinzMinusx * siny;
  645. result.z = sinxPlusz * cosy;
  646. result.w = cosxPlusz * cosy;
  647. return result;
  648. };
  649. Vector3.prototype.addInPlace = function (otherVector) {
  650. this.x += otherVector.x;
  651. this.y += otherVector.y;
  652. this.z += otherVector.z;
  653. return this;
  654. };
  655. Vector3.prototype.add = function (otherVector) {
  656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  657. };
  658. Vector3.prototype.addToRef = function (otherVector, result) {
  659. result.x = this.x + otherVector.x;
  660. result.y = this.y + otherVector.y;
  661. result.z = this.z + otherVector.z;
  662. return this;
  663. };
  664. Vector3.prototype.subtractInPlace = function (otherVector) {
  665. this.x -= otherVector.x;
  666. this.y -= otherVector.y;
  667. this.z -= otherVector.z;
  668. return this;
  669. };
  670. Vector3.prototype.subtract = function (otherVector) {
  671. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  672. };
  673. Vector3.prototype.subtractToRef = function (otherVector, result) {
  674. result.x = this.x - otherVector.x;
  675. result.y = this.y - otherVector.y;
  676. result.z = this.z - otherVector.z;
  677. return this;
  678. };
  679. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  680. return new Vector3(this.x - x, this.y - y, this.z - z);
  681. };
  682. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  683. result.x = this.x - x;
  684. result.y = this.y - y;
  685. result.z = this.z - z;
  686. return this;
  687. };
  688. Vector3.prototype.negate = function () {
  689. return new Vector3(-this.x, -this.y, -this.z);
  690. };
  691. Vector3.prototype.scaleInPlace = function (scale) {
  692. this.x *= scale;
  693. this.y *= scale;
  694. this.z *= scale;
  695. return this;
  696. };
  697. Vector3.prototype.scale = function (scale) {
  698. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  699. };
  700. Vector3.prototype.scaleToRef = function (scale, result) {
  701. result.x = this.x * scale;
  702. result.y = this.y * scale;
  703. result.z = this.z * scale;
  704. };
  705. Vector3.prototype.equals = function (otherVector) {
  706. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  707. };
  708. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  709. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  710. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  711. };
  712. Vector3.prototype.equalsToFloats = function (x, y, z) {
  713. return this.x === x && this.y === y && this.z === z;
  714. };
  715. Vector3.prototype.multiplyInPlace = function (otherVector) {
  716. this.x *= otherVector.x;
  717. this.y *= otherVector.y;
  718. this.z *= otherVector.z;
  719. return this;
  720. };
  721. Vector3.prototype.multiply = function (otherVector) {
  722. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  723. };
  724. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  725. result.x = this.x * otherVector.x;
  726. result.y = this.y * otherVector.y;
  727. result.z = this.z * otherVector.z;
  728. return this;
  729. };
  730. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  731. return new Vector3(this.x * x, this.y * y, this.z * z);
  732. };
  733. Vector3.prototype.divide = function (otherVector) {
  734. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  735. };
  736. Vector3.prototype.divideToRef = function (otherVector, result) {
  737. result.x = this.x / otherVector.x;
  738. result.y = this.y / otherVector.y;
  739. result.z = this.z / otherVector.z;
  740. return this;
  741. };
  742. Vector3.prototype.MinimizeInPlace = function (other) {
  743. if (other.x < this.x)
  744. this.x = other.x;
  745. if (other.y < this.y)
  746. this.y = other.y;
  747. if (other.z < this.z)
  748. this.z = other.z;
  749. return this;
  750. };
  751. Vector3.prototype.MaximizeInPlace = function (other) {
  752. if (other.x > this.x)
  753. this.x = other.x;
  754. if (other.y > this.y)
  755. this.y = other.y;
  756. if (other.z > this.z)
  757. this.z = other.z;
  758. return this;
  759. };
  760. // Properties
  761. Vector3.prototype.length = function () {
  762. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  763. };
  764. Vector3.prototype.lengthSquared = function () {
  765. return (this.x * this.x + this.y * this.y + this.z * this.z);
  766. };
  767. // Methods
  768. Vector3.prototype.normalize = function () {
  769. var len = this.length();
  770. if (len === 0 || len === 1.0)
  771. return this;
  772. var num = 1.0 / len;
  773. this.x *= num;
  774. this.y *= num;
  775. this.z *= num;
  776. return this;
  777. };
  778. Vector3.prototype.clone = function () {
  779. return new Vector3(this.x, this.y, this.z);
  780. };
  781. Vector3.prototype.copyFrom = function (source) {
  782. this.x = source.x;
  783. this.y = source.y;
  784. this.z = source.z;
  785. return this;
  786. };
  787. Vector3.prototype.copyFromFloats = function (x, y, z) {
  788. this.x = x;
  789. this.y = y;
  790. this.z = z;
  791. return this;
  792. };
  793. // Statics
  794. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  795. var d0 = Vector3.Dot(vector0, axis) - size;
  796. var d1 = Vector3.Dot(vector1, axis) - size;
  797. var s = d0 / (d0 - d1);
  798. return s;
  799. };
  800. Vector3.FromArray = function (array, offset) {
  801. if (!offset) {
  802. offset = 0;
  803. }
  804. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  805. };
  806. Vector3.FromFloatArray = function (array, offset) {
  807. if (!offset) {
  808. offset = 0;
  809. }
  810. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  811. };
  812. Vector3.FromArrayToRef = function (array, offset, result) {
  813. result.x = array[offset];
  814. result.y = array[offset + 1];
  815. result.z = array[offset + 2];
  816. };
  817. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  818. result.x = array[offset];
  819. result.y = array[offset + 1];
  820. result.z = array[offset + 2];
  821. };
  822. Vector3.FromFloatsToRef = function (x, y, z, result) {
  823. result.x = x;
  824. result.y = y;
  825. result.z = z;
  826. };
  827. Vector3.Zero = function () {
  828. return new Vector3(0, 0, 0);
  829. };
  830. Vector3.Up = function () {
  831. return new Vector3(0, 1.0, 0);
  832. };
  833. Vector3.TransformCoordinates = function (vector, transformation) {
  834. var result = Vector3.Zero();
  835. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  836. return result;
  837. };
  838. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  839. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  840. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  841. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  842. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  843. result.x = x / w;
  844. result.y = y / w;
  845. result.z = z / w;
  846. };
  847. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  848. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  849. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  850. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  851. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  852. result.x = rx / rw;
  853. result.y = ry / rw;
  854. result.z = rz / rw;
  855. };
  856. Vector3.TransformNormal = function (vector, transformation) {
  857. var result = Vector3.Zero();
  858. Vector3.TransformNormalToRef(vector, transformation, result);
  859. return result;
  860. };
  861. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  862. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  863. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  864. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  865. };
  866. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  867. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  868. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  869. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  870. };
  871. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  872. var squared = amount * amount;
  873. var cubed = amount * squared;
  874. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  875. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  876. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  877. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  878. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  879. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  880. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  881. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  882. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  883. return new Vector3(x, y, z);
  884. };
  885. Vector3.Clamp = function (value, min, max) {
  886. var x = value.x;
  887. x = (x > max.x) ? max.x : x;
  888. x = (x < min.x) ? min.x : x;
  889. var y = value.y;
  890. y = (y > max.y) ? max.y : y;
  891. y = (y < min.y) ? min.y : y;
  892. var z = value.z;
  893. z = (z > max.z) ? max.z : z;
  894. z = (z < min.z) ? min.z : z;
  895. return new Vector3(x, y, z);
  896. };
  897. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  898. var squared = amount * amount;
  899. var cubed = amount * squared;
  900. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  901. var part2 = (-2.0 * cubed) + (3.0 * squared);
  902. var part3 = (cubed - (2.0 * squared)) + amount;
  903. var part4 = cubed - squared;
  904. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  905. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  906. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  907. return new Vector3(x, y, z);
  908. };
  909. Vector3.Lerp = function (start, end, amount) {
  910. var x = start.x + ((end.x - start.x) * amount);
  911. var y = start.y + ((end.y - start.y) * amount);
  912. var z = start.z + ((end.z - start.z) * amount);
  913. return new Vector3(x, y, z);
  914. };
  915. Vector3.Dot = function (left, right) {
  916. return (left.x * right.x + left.y * right.y + left.z * right.z);
  917. };
  918. Vector3.Cross = function (left, right) {
  919. var result = Vector3.Zero();
  920. Vector3.CrossToRef(left, right, result);
  921. return result;
  922. };
  923. Vector3.CrossToRef = function (left, right, result) {
  924. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  925. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  926. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  927. result.copyFrom(Tmp.Vector3[0]);
  928. };
  929. Vector3.Normalize = function (vector) {
  930. var result = Vector3.Zero();
  931. Vector3.NormalizeToRef(vector, result);
  932. return result;
  933. };
  934. Vector3.NormalizeToRef = function (vector, result) {
  935. result.copyFrom(vector);
  936. result.normalize();
  937. };
  938. Vector3.Project = function (vector, world, transform, viewport) {
  939. var cw = viewport.width;
  940. var ch = viewport.height;
  941. var cx = viewport.x;
  942. var cy = viewport.y;
  943. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  944. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1, viewportMatrix);
  945. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  946. world.multiplyToRef(transform, matrix);
  947. matrix.multiplyToRef(viewportMatrix, matrix);
  948. return Vector3.TransformCoordinates(vector, matrix);
  949. };
  950. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  951. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  952. world.multiplyToRef(transform, matrix);
  953. matrix.invert();
  954. source.x = source.x / viewportWidth * 2 - 1;
  955. source.y = -(source.y / viewportHeight * 2 - 1);
  956. var vector = Vector3.TransformCoordinates(source, matrix);
  957. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  958. if (MathTools.WithinEpsilon(num, 1.0)) {
  959. vector = vector.scale(1.0 / num);
  960. }
  961. return vector;
  962. };
  963. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  964. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  965. world.multiplyToRef(view, matrix);
  966. matrix.multiplyToRef(projection, matrix);
  967. matrix.invert();
  968. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), source.z);
  969. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  970. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  971. if (MathTools.WithinEpsilon(num, 1.0)) {
  972. vector = vector.scale(1.0 / num);
  973. }
  974. return vector;
  975. };
  976. Vector3.Minimize = function (left, right) {
  977. var min = left.clone();
  978. min.MinimizeInPlace(right);
  979. return min;
  980. };
  981. Vector3.Maximize = function (left, right) {
  982. var max = left.clone();
  983. max.MaximizeInPlace(right);
  984. return max;
  985. };
  986. Vector3.Distance = function (value1, value2) {
  987. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  988. };
  989. Vector3.DistanceSquared = function (value1, value2) {
  990. var x = value1.x - value2.x;
  991. var y = value1.y - value2.y;
  992. var z = value1.z - value2.z;
  993. return (x * x) + (y * y) + (z * z);
  994. };
  995. Vector3.Center = function (value1, value2) {
  996. var center = value1.add(value2);
  997. center.scaleInPlace(0.5);
  998. return center;
  999. };
  1000. /**
  1001. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1002. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1003. * to something in order to rotate it from its local system to the given target system.
  1004. */
  1005. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1006. var rotation = Vector3.Zero();
  1007. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1008. return rotation;
  1009. };
  1010. /**
  1011. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1012. */
  1013. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1014. var u = axis1.normalize();
  1015. var w = axis3.normalize();
  1016. // world axis
  1017. var X = Axis.X;
  1018. var Y = Axis.Y;
  1019. // equation unknowns and vars
  1020. var yaw = 0.0;
  1021. var pitch = 0.0;
  1022. var roll = 0.0;
  1023. var x = 0.0;
  1024. var y = 0.0;
  1025. var z = 0.0;
  1026. var t = 0.0;
  1027. var sign = -1.0;
  1028. var nbRevert = 0;
  1029. var cross = Tmp.Vector3[0];
  1030. var dot = 0.0;
  1031. // step 1 : rotation around w
  1032. // Rv3(u) = u1, and u1 belongs to plane xOz
  1033. // Rv3(w) = w1 = w invariant
  1034. var u1 = Tmp.Vector3[1];
  1035. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1036. z = 1.0;
  1037. }
  1038. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1039. x = 1.0;
  1040. }
  1041. else {
  1042. t = w.z / w.x;
  1043. x = -t * Math.sqrt(1 / (1 + t * t));
  1044. z = Math.sqrt(1 / (1 + t * t));
  1045. }
  1046. u1.x = x;
  1047. u1.y = y;
  1048. u1.z = z;
  1049. u1.normalize();
  1050. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1051. cross.normalize();
  1052. if (Vector3.Dot(w, cross) < 0) {
  1053. sign = 1.0;
  1054. }
  1055. dot = Vector3.Dot(u, u1);
  1056. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1057. roll = Math.acos(dot) * sign;
  1058. if (Vector3.Dot(u1, X) < 0) {
  1059. roll = Math.PI + roll;
  1060. u1 = u1.scaleInPlace(-1);
  1061. nbRevert++;
  1062. }
  1063. // step 2 : rotate around u1
  1064. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1065. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1066. var w2 = Tmp.Vector3[2];
  1067. var v2 = Tmp.Vector3[3];
  1068. x = 0.0;
  1069. y = 0.0;
  1070. z = 0.0;
  1071. sign = -1.0;
  1072. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1073. x = 1.0;
  1074. }
  1075. else {
  1076. t = u1.z / u1.x;
  1077. x = -t * Math.sqrt(1 / (1 + t * t));
  1078. z = Math.sqrt(1 / (1 + t * t));
  1079. }
  1080. w2.x = x;
  1081. w2.y = y;
  1082. w2.z = z;
  1083. w2.normalize();
  1084. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1085. v2.normalize();
  1086. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1087. cross.normalize();
  1088. if (Vector3.Dot(u1, cross) < 0) {
  1089. sign = 1.0;
  1090. }
  1091. dot = Vector3.Dot(w, w2);
  1092. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1093. pitch = Math.acos(dot) * sign;
  1094. if (Vector3.Dot(v2, Y) < 0) {
  1095. pitch = Math.PI + pitch;
  1096. nbRevert++;
  1097. }
  1098. // step 3 : rotate around v2
  1099. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1100. sign = -1.0;
  1101. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1102. cross.normalize();
  1103. if (Vector3.Dot(cross, Y) < 0) {
  1104. sign = 1.0;
  1105. }
  1106. dot = Vector3.Dot(u1, X);
  1107. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1108. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1109. if (dot < 0 && nbRevert < 2) {
  1110. yaw = Math.PI + yaw;
  1111. }
  1112. ref.x = pitch;
  1113. ref.y = yaw;
  1114. ref.z = roll;
  1115. };
  1116. return Vector3;
  1117. }());
  1118. BABYLON.Vector3 = Vector3;
  1119. //Vector4 class created for EulerAngle class conversion to Quaternion
  1120. var Vector4 = (function () {
  1121. function Vector4(x, y, z, w) {
  1122. this.x = x;
  1123. this.y = y;
  1124. this.z = z;
  1125. this.w = w;
  1126. }
  1127. Vector4.prototype.toString = function () {
  1128. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  1129. };
  1130. Vector4.prototype.getClassName = function () {
  1131. return "Vector4";
  1132. };
  1133. Vector4.prototype.getHashCode = function () {
  1134. var hash = this.x || 0;
  1135. hash = (hash * 397) ^ (this.y || 0);
  1136. hash = (hash * 397) ^ (this.z || 0);
  1137. hash = (hash * 397) ^ (this.w || 0);
  1138. return hash;
  1139. };
  1140. // Operators
  1141. Vector4.prototype.asArray = function () {
  1142. var result = [];
  1143. this.toArray(result, 0);
  1144. return result;
  1145. };
  1146. Vector4.prototype.toArray = function (array, index) {
  1147. if (index === undefined) {
  1148. index = 0;
  1149. }
  1150. array[index] = this.x;
  1151. array[index + 1] = this.y;
  1152. array[index + 2] = this.z;
  1153. array[index + 3] = this.w;
  1154. return this;
  1155. };
  1156. Vector4.prototype.addInPlace = function (otherVector) {
  1157. this.x += otherVector.x;
  1158. this.y += otherVector.y;
  1159. this.z += otherVector.z;
  1160. this.w += otherVector.w;
  1161. return this;
  1162. };
  1163. Vector4.prototype.add = function (otherVector) {
  1164. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1165. };
  1166. Vector4.prototype.addToRef = function (otherVector, result) {
  1167. result.x = this.x + otherVector.x;
  1168. result.y = this.y + otherVector.y;
  1169. result.z = this.z + otherVector.z;
  1170. result.w = this.w + otherVector.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.subtractInPlace = function (otherVector) {
  1174. this.x -= otherVector.x;
  1175. this.y -= otherVector.y;
  1176. this.z -= otherVector.z;
  1177. this.w -= otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.subtract = function (otherVector) {
  1181. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1182. };
  1183. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1184. result.x = this.x - otherVector.x;
  1185. result.y = this.y - otherVector.y;
  1186. result.z = this.z - otherVector.z;
  1187. result.w = this.w - otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1191. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1192. };
  1193. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1194. result.x = this.x - x;
  1195. result.y = this.y - y;
  1196. result.z = this.z - z;
  1197. result.w = this.w - w;
  1198. return this;
  1199. };
  1200. Vector4.prototype.negate = function () {
  1201. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1202. };
  1203. Vector4.prototype.scaleInPlace = function (scale) {
  1204. this.x *= scale;
  1205. this.y *= scale;
  1206. this.z *= scale;
  1207. this.w *= scale;
  1208. return this;
  1209. };
  1210. Vector4.prototype.scale = function (scale) {
  1211. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1212. };
  1213. Vector4.prototype.scaleToRef = function (scale, result) {
  1214. result.x = this.x * scale;
  1215. result.y = this.y * scale;
  1216. result.z = this.z * scale;
  1217. result.w = this.w * scale;
  1218. };
  1219. Vector4.prototype.equals = function (otherVector) {
  1220. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1221. };
  1222. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1223. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1224. return otherVector
  1225. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1226. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1227. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1228. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1229. };
  1230. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1231. return this.x === x && this.y === y && this.z === z && this.w === w;
  1232. };
  1233. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1234. this.x *= otherVector.x;
  1235. this.y *= otherVector.y;
  1236. this.z *= otherVector.z;
  1237. this.w *= otherVector.w;
  1238. return this;
  1239. };
  1240. Vector4.prototype.multiply = function (otherVector) {
  1241. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1242. };
  1243. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1244. result.x = this.x * otherVector.x;
  1245. result.y = this.y * otherVector.y;
  1246. result.z = this.z * otherVector.z;
  1247. result.w = this.w * otherVector.w;
  1248. return this;
  1249. };
  1250. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1251. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1252. };
  1253. Vector4.prototype.divide = function (otherVector) {
  1254. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1255. };
  1256. Vector4.prototype.divideToRef = function (otherVector, result) {
  1257. result.x = this.x / otherVector.x;
  1258. result.y = this.y / otherVector.y;
  1259. result.z = this.z / otherVector.z;
  1260. result.w = this.w / otherVector.w;
  1261. return this;
  1262. };
  1263. Vector4.prototype.MinimizeInPlace = function (other) {
  1264. if (other.x < this.x)
  1265. this.x = other.x;
  1266. if (other.y < this.y)
  1267. this.y = other.y;
  1268. if (other.z < this.z)
  1269. this.z = other.z;
  1270. if (other.w < this.w)
  1271. this.w = other.w;
  1272. return this;
  1273. };
  1274. Vector4.prototype.MaximizeInPlace = function (other) {
  1275. if (other.x > this.x)
  1276. this.x = other.x;
  1277. if (other.y > this.y)
  1278. this.y = other.y;
  1279. if (other.z > this.z)
  1280. this.z = other.z;
  1281. if (other.w > this.w)
  1282. this.w = other.w;
  1283. return this;
  1284. };
  1285. // Properties
  1286. Vector4.prototype.length = function () {
  1287. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1288. };
  1289. Vector4.prototype.lengthSquared = function () {
  1290. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1291. };
  1292. // Methods
  1293. Vector4.prototype.normalize = function () {
  1294. var len = this.length();
  1295. if (len === 0)
  1296. return this;
  1297. var num = 1.0 / len;
  1298. this.x *= num;
  1299. this.y *= num;
  1300. this.z *= num;
  1301. this.w *= num;
  1302. return this;
  1303. };
  1304. Vector4.prototype.toVector3 = function () {
  1305. return new Vector3(this.x, this.y, this.z);
  1306. };
  1307. Vector4.prototype.clone = function () {
  1308. return new Vector4(this.x, this.y, this.z, this.w);
  1309. };
  1310. Vector4.prototype.copyFrom = function (source) {
  1311. this.x = source.x;
  1312. this.y = source.y;
  1313. this.z = source.z;
  1314. this.w = source.w;
  1315. return this;
  1316. };
  1317. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1318. this.x = x;
  1319. this.y = y;
  1320. this.z = z;
  1321. this.w = w;
  1322. return this;
  1323. };
  1324. // Statics
  1325. Vector4.FromArray = function (array, offset) {
  1326. if (!offset) {
  1327. offset = 0;
  1328. }
  1329. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1330. };
  1331. Vector4.FromArrayToRef = function (array, offset, result) {
  1332. result.x = array[offset];
  1333. result.y = array[offset + 1];
  1334. result.z = array[offset + 2];
  1335. result.w = array[offset + 3];
  1336. };
  1337. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1338. result.x = array[offset];
  1339. result.y = array[offset + 1];
  1340. result.z = array[offset + 2];
  1341. result.w = array[offset + 3];
  1342. };
  1343. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1344. result.x = x;
  1345. result.y = y;
  1346. result.z = z;
  1347. result.w = w;
  1348. };
  1349. Vector4.Zero = function () {
  1350. return new Vector4(0, 0, 0, 0);
  1351. };
  1352. Vector4.Normalize = function (vector) {
  1353. var result = Vector4.Zero();
  1354. Vector4.NormalizeToRef(vector, result);
  1355. return result;
  1356. };
  1357. Vector4.NormalizeToRef = function (vector, result) {
  1358. result.copyFrom(vector);
  1359. result.normalize();
  1360. };
  1361. Vector4.Minimize = function (left, right) {
  1362. var min = left.clone();
  1363. min.MinimizeInPlace(right);
  1364. return min;
  1365. };
  1366. Vector4.Maximize = function (left, right) {
  1367. var max = left.clone();
  1368. max.MaximizeInPlace(right);
  1369. return max;
  1370. };
  1371. Vector4.Distance = function (value1, value2) {
  1372. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1373. };
  1374. Vector4.DistanceSquared = function (value1, value2) {
  1375. var x = value1.x - value2.x;
  1376. var y = value1.y - value2.y;
  1377. var z = value1.z - value2.z;
  1378. var w = value1.w - value2.w;
  1379. return (x * x) + (y * y) + (z * z) + (w * w);
  1380. };
  1381. Vector4.Center = function (value1, value2) {
  1382. var center = value1.add(value2);
  1383. center.scaleInPlace(0.5);
  1384. return center;
  1385. };
  1386. return Vector4;
  1387. }());
  1388. BABYLON.Vector4 = Vector4;
  1389. var Size = (function () {
  1390. function Size(width, height) {
  1391. this.width = width;
  1392. this.height = height;
  1393. }
  1394. Size.prototype.toString = function () {
  1395. return "{W: " + this.width + ", H: " + this.height + "}";
  1396. };
  1397. Size.prototype.getClassName = function () {
  1398. return "Size";
  1399. };
  1400. Size.prototype.getHashCode = function () {
  1401. var hash = this.width || 0;
  1402. hash = (hash * 397) ^ (this.height || 0);
  1403. return hash;
  1404. };
  1405. Size.prototype.copyFrom = function (src) {
  1406. this.width = src.width;
  1407. this.height = src.height;
  1408. };
  1409. Size.prototype.copyFromFloats = function (width, height) {
  1410. this.width = width;
  1411. this.height = height;
  1412. };
  1413. Size.prototype.multiplyByFloats = function (w, h) {
  1414. return new Size(this.width * w, this.height * h);
  1415. };
  1416. Size.prototype.clone = function () {
  1417. return new Size(this.width, this.height);
  1418. };
  1419. Size.prototype.equals = function (other) {
  1420. if (!other) {
  1421. return false;
  1422. }
  1423. return (this.width === other.width) && (this.height === other.height);
  1424. };
  1425. Object.defineProperty(Size.prototype, "surface", {
  1426. get: function () {
  1427. return this.width * this.height;
  1428. },
  1429. enumerable: true,
  1430. configurable: true
  1431. });
  1432. Size.Zero = function () {
  1433. return new Size(0, 0);
  1434. };
  1435. Size.prototype.add = function (otherSize) {
  1436. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1437. return r;
  1438. };
  1439. Size.prototype.substract = function (otherSize) {
  1440. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1441. return r;
  1442. };
  1443. Size.Lerp = function (start, end, amount) {
  1444. var w = start.width + ((end.width - start.width) * amount);
  1445. var h = start.height + ((end.height - start.height) * amount);
  1446. return new Size(w, h);
  1447. };
  1448. return Size;
  1449. }());
  1450. BABYLON.Size = Size;
  1451. var Quaternion = (function () {
  1452. function Quaternion(x, y, z, w) {
  1453. if (x === void 0) { x = 0; }
  1454. if (y === void 0) { y = 0; }
  1455. if (z === void 0) { z = 0; }
  1456. if (w === void 0) { w = 1; }
  1457. this.x = x;
  1458. this.y = y;
  1459. this.z = z;
  1460. this.w = w;
  1461. }
  1462. Quaternion.prototype.toString = function () {
  1463. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1464. };
  1465. Quaternion.prototype.getClassName = function () {
  1466. return "Quaternion";
  1467. };
  1468. Quaternion.prototype.getHashCode = function () {
  1469. var hash = this.x || 0;
  1470. hash = (hash * 397) ^ (this.y || 0);
  1471. hash = (hash * 397) ^ (this.z || 0);
  1472. hash = (hash * 397) ^ (this.w || 0);
  1473. return hash;
  1474. };
  1475. Quaternion.prototype.asArray = function () {
  1476. return [this.x, this.y, this.z, this.w];
  1477. };
  1478. Quaternion.prototype.equals = function (otherQuaternion) {
  1479. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1480. };
  1481. Quaternion.prototype.clone = function () {
  1482. return new Quaternion(this.x, this.y, this.z, this.w);
  1483. };
  1484. Quaternion.prototype.copyFrom = function (other) {
  1485. this.x = other.x;
  1486. this.y = other.y;
  1487. this.z = other.z;
  1488. this.w = other.w;
  1489. return this;
  1490. };
  1491. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1492. this.x = x;
  1493. this.y = y;
  1494. this.z = z;
  1495. this.w = w;
  1496. return this;
  1497. };
  1498. Quaternion.prototype.add = function (other) {
  1499. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1500. };
  1501. Quaternion.prototype.subtract = function (other) {
  1502. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1503. };
  1504. Quaternion.prototype.scale = function (value) {
  1505. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1506. };
  1507. Quaternion.prototype.multiply = function (q1) {
  1508. var result = new Quaternion(0, 0, 0, 1.0);
  1509. this.multiplyToRef(q1, result);
  1510. return result;
  1511. };
  1512. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1513. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1514. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1515. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1516. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1517. result.copyFromFloats(x, y, z, w);
  1518. return this;
  1519. };
  1520. Quaternion.prototype.multiplyInPlace = function (q1) {
  1521. this.multiplyToRef(q1, this);
  1522. return this;
  1523. };
  1524. Quaternion.prototype.conjugateToRef = function (ref) {
  1525. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1526. return this;
  1527. };
  1528. Quaternion.prototype.conjugateInPlace = function () {
  1529. this.x *= -1;
  1530. this.y *= -1;
  1531. this.z *= -1;
  1532. return this;
  1533. };
  1534. Quaternion.prototype.conjugate = function () {
  1535. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1536. return result;
  1537. };
  1538. Quaternion.prototype.length = function () {
  1539. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1540. };
  1541. Quaternion.prototype.normalize = function () {
  1542. var length = 1.0 / this.length();
  1543. this.x *= length;
  1544. this.y *= length;
  1545. this.z *= length;
  1546. this.w *= length;
  1547. return this;
  1548. };
  1549. Quaternion.prototype.toEulerAngles = function (order) {
  1550. if (order === void 0) { order = "YZX"; }
  1551. var result = Vector3.Zero();
  1552. this.toEulerAnglesToRef(result, order);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1556. if (order === void 0) { order = "YZX"; }
  1557. var heading, attitude, bank;
  1558. var x = this.x, y = this.y, z = this.z, w = this.w;
  1559. switch (order) {
  1560. case "YZX":
  1561. var test = x * y + z * w;
  1562. if (test > 0.499) {
  1563. heading = 2 * Math.atan2(x, w);
  1564. attitude = Math.PI / 2;
  1565. bank = 0;
  1566. }
  1567. if (test < -0.499) {
  1568. heading = -2 * Math.atan2(x, w);
  1569. attitude = -Math.PI / 2;
  1570. bank = 0;
  1571. }
  1572. if (isNaN(heading)) {
  1573. var sqx = x * x;
  1574. var sqy = y * y;
  1575. var sqz = z * z;
  1576. heading = Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz); // Heading
  1577. attitude = Math.asin(2 * test); // attitude
  1578. bank = Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz); // bank
  1579. }
  1580. break;
  1581. default:
  1582. throw new Error("Euler order " + order + " not supported yet.");
  1583. }
  1584. result.y = heading;
  1585. result.z = attitude;
  1586. result.x = bank;
  1587. return this;
  1588. };
  1589. ;
  1590. Quaternion.prototype.toRotationMatrix = function (result) {
  1591. var xx = this.x * this.x;
  1592. var yy = this.y * this.y;
  1593. var zz = this.z * this.z;
  1594. var xy = this.x * this.y;
  1595. var zw = this.z * this.w;
  1596. var zx = this.z * this.x;
  1597. var yw = this.y * this.w;
  1598. var yz = this.y * this.z;
  1599. var xw = this.x * this.w;
  1600. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1601. result.m[1] = 2.0 * (xy + zw);
  1602. result.m[2] = 2.0 * (zx - yw);
  1603. result.m[3] = 0;
  1604. result.m[4] = 2.0 * (xy - zw);
  1605. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1606. result.m[6] = 2.0 * (yz + xw);
  1607. result.m[7] = 0;
  1608. result.m[8] = 2.0 * (zx + yw);
  1609. result.m[9] = 2.0 * (yz - xw);
  1610. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1611. result.m[11] = 0;
  1612. result.m[12] = 0;
  1613. result.m[13] = 0;
  1614. result.m[14] = 0;
  1615. result.m[15] = 1.0;
  1616. return this;
  1617. };
  1618. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1619. Quaternion.FromRotationMatrixToRef(matrix, this);
  1620. return this;
  1621. };
  1622. // Statics
  1623. Quaternion.FromRotationMatrix = function (matrix) {
  1624. var result = new Quaternion();
  1625. Quaternion.FromRotationMatrixToRef(matrix, result);
  1626. return result;
  1627. };
  1628. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1629. var data = matrix.m;
  1630. var m11 = data[0], m12 = data[4], m13 = data[8];
  1631. var m21 = data[1], m22 = data[5], m23 = data[9];
  1632. var m31 = data[2], m32 = data[6], m33 = data[10];
  1633. var trace = m11 + m22 + m33;
  1634. var s;
  1635. if (trace > 0) {
  1636. s = 0.5 / Math.sqrt(trace + 1.0);
  1637. result.w = 0.25 / s;
  1638. result.x = (m32 - m23) * s;
  1639. result.y = (m13 - m31) * s;
  1640. result.z = (m21 - m12) * s;
  1641. }
  1642. else if (m11 > m22 && m11 > m33) {
  1643. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1644. result.w = (m32 - m23) / s;
  1645. result.x = 0.25 * s;
  1646. result.y = (m12 + m21) / s;
  1647. result.z = (m13 + m31) / s;
  1648. }
  1649. else if (m22 > m33) {
  1650. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1651. result.w = (m13 - m31) / s;
  1652. result.x = (m12 + m21) / s;
  1653. result.y = 0.25 * s;
  1654. result.z = (m23 + m32) / s;
  1655. }
  1656. else {
  1657. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1658. result.w = (m21 - m12) / s;
  1659. result.x = (m13 + m31) / s;
  1660. result.y = (m23 + m32) / s;
  1661. result.z = 0.25 * s;
  1662. }
  1663. };
  1664. Quaternion.Inverse = function (q) {
  1665. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1666. };
  1667. Quaternion.Identity = function () {
  1668. return new Quaternion(0, 0, 0, 1);
  1669. };
  1670. Quaternion.RotationAxis = function (axis, angle) {
  1671. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1672. };
  1673. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1674. var sin = Math.sin(angle / 2);
  1675. axis.normalize();
  1676. result.w = Math.cos(angle / 2);
  1677. result.x = axis.x * sin;
  1678. result.y = axis.y * sin;
  1679. result.z = axis.z * sin;
  1680. return result;
  1681. };
  1682. Quaternion.FromArray = function (array, offset) {
  1683. if (!offset) {
  1684. offset = 0;
  1685. }
  1686. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1687. };
  1688. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1689. var q = new Quaternion();
  1690. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1691. return q;
  1692. };
  1693. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1694. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1695. var halfRoll = roll * 0.5;
  1696. var halfPitch = pitch * 0.5;
  1697. var halfYaw = yaw * 0.5;
  1698. var sinRoll = Math.sin(halfRoll);
  1699. var cosRoll = Math.cos(halfRoll);
  1700. var sinPitch = Math.sin(halfPitch);
  1701. var cosPitch = Math.cos(halfPitch);
  1702. var sinYaw = Math.sin(halfYaw);
  1703. var cosYaw = Math.cos(halfYaw);
  1704. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1705. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1706. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1707. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1708. };
  1709. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1710. var result = new Quaternion();
  1711. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1712. return result;
  1713. };
  1714. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1715. // Produces a quaternion from Euler angles in the z-x-z orientation
  1716. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1717. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1718. var halfBeta = beta * 0.5;
  1719. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1720. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1721. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1722. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1723. };
  1724. Quaternion.Slerp = function (left, right, amount) {
  1725. var num2;
  1726. var num3;
  1727. var num = amount;
  1728. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1729. var flag = false;
  1730. if (num4 < 0) {
  1731. flag = true;
  1732. num4 = -num4;
  1733. }
  1734. if (num4 > 0.999999) {
  1735. num3 = 1 - num;
  1736. num2 = flag ? -num : num;
  1737. }
  1738. else {
  1739. var num5 = Math.acos(num4);
  1740. var num6 = (1.0 / Math.sin(num5));
  1741. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1742. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1743. }
  1744. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1745. };
  1746. return Quaternion;
  1747. }());
  1748. BABYLON.Quaternion = Quaternion;
  1749. var Matrix = (function () {
  1750. function Matrix() {
  1751. this.m = new Float32Array(16);
  1752. }
  1753. // Properties
  1754. Matrix.prototype.isIdentity = function () {
  1755. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1756. return false;
  1757. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1758. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1759. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1760. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1761. return false;
  1762. return true;
  1763. };
  1764. Matrix.prototype.determinant = function () {
  1765. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1766. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1767. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1768. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1769. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1770. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1771. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1772. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1773. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1774. };
  1775. // Methods
  1776. Matrix.prototype.toArray = function () {
  1777. return this.m;
  1778. };
  1779. Matrix.prototype.asArray = function () {
  1780. return this.toArray();
  1781. };
  1782. Matrix.prototype.invert = function () {
  1783. this.invertToRef(this);
  1784. return this;
  1785. };
  1786. Matrix.prototype.reset = function () {
  1787. for (var index = 0; index < 16; index++) {
  1788. this.m[index] = 0;
  1789. }
  1790. return this;
  1791. };
  1792. Matrix.prototype.add = function (other) {
  1793. var result = new Matrix();
  1794. this.addToRef(other, result);
  1795. return result;
  1796. };
  1797. Matrix.prototype.addToRef = function (other, result) {
  1798. for (var index = 0; index < 16; index++) {
  1799. result.m[index] = this.m[index] + other.m[index];
  1800. }
  1801. return this;
  1802. };
  1803. Matrix.prototype.addToSelf = function (other) {
  1804. for (var index = 0; index < 16; index++) {
  1805. this.m[index] += other.m[index];
  1806. }
  1807. return this;
  1808. };
  1809. Matrix.prototype.invertToRef = function (other) {
  1810. var l1 = this.m[0];
  1811. var l2 = this.m[1];
  1812. var l3 = this.m[2];
  1813. var l4 = this.m[3];
  1814. var l5 = this.m[4];
  1815. var l6 = this.m[5];
  1816. var l7 = this.m[6];
  1817. var l8 = this.m[7];
  1818. var l9 = this.m[8];
  1819. var l10 = this.m[9];
  1820. var l11 = this.m[10];
  1821. var l12 = this.m[11];
  1822. var l13 = this.m[12];
  1823. var l14 = this.m[13];
  1824. var l15 = this.m[14];
  1825. var l16 = this.m[15];
  1826. var l17 = (l11 * l16) - (l12 * l15);
  1827. var l18 = (l10 * l16) - (l12 * l14);
  1828. var l19 = (l10 * l15) - (l11 * l14);
  1829. var l20 = (l9 * l16) - (l12 * l13);
  1830. var l21 = (l9 * l15) - (l11 * l13);
  1831. var l22 = (l9 * l14) - (l10 * l13);
  1832. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1833. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1834. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1835. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1836. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1837. var l28 = (l7 * l16) - (l8 * l15);
  1838. var l29 = (l6 * l16) - (l8 * l14);
  1839. var l30 = (l6 * l15) - (l7 * l14);
  1840. var l31 = (l5 * l16) - (l8 * l13);
  1841. var l32 = (l5 * l15) - (l7 * l13);
  1842. var l33 = (l5 * l14) - (l6 * l13);
  1843. var l34 = (l7 * l12) - (l8 * l11);
  1844. var l35 = (l6 * l12) - (l8 * l10);
  1845. var l36 = (l6 * l11) - (l7 * l10);
  1846. var l37 = (l5 * l12) - (l8 * l9);
  1847. var l38 = (l5 * l11) - (l7 * l9);
  1848. var l39 = (l5 * l10) - (l6 * l9);
  1849. other.m[0] = l23 * l27;
  1850. other.m[4] = l24 * l27;
  1851. other.m[8] = l25 * l27;
  1852. other.m[12] = l26 * l27;
  1853. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1854. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1855. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1856. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1857. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1858. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1859. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1860. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1861. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1862. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1863. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1864. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1865. return this;
  1866. };
  1867. Matrix.prototype.setTranslation = function (vector3) {
  1868. this.m[12] = vector3.x;
  1869. this.m[13] = vector3.y;
  1870. this.m[14] = vector3.z;
  1871. return this;
  1872. };
  1873. Matrix.prototype.getTranslation = function () {
  1874. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1875. };
  1876. Matrix.prototype.multiply = function (other) {
  1877. var result = new Matrix();
  1878. this.multiplyToRef(other, result);
  1879. return result;
  1880. };
  1881. Matrix.prototype.copyFrom = function (other) {
  1882. for (var index = 0; index < 16; index++) {
  1883. this.m[index] = other.m[index];
  1884. }
  1885. return this;
  1886. };
  1887. Matrix.prototype.copyToArray = function (array, offset) {
  1888. if (offset === void 0) { offset = 0; }
  1889. for (var index = 0; index < 16; index++) {
  1890. array[offset + index] = this.m[index];
  1891. }
  1892. return this;
  1893. };
  1894. Matrix.prototype.multiplyToRef = function (other, result) {
  1895. this.multiplyToArray(other, result.m, 0);
  1896. return this;
  1897. };
  1898. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1899. var tm0 = this.m[0];
  1900. var tm1 = this.m[1];
  1901. var tm2 = this.m[2];
  1902. var tm3 = this.m[3];
  1903. var tm4 = this.m[4];
  1904. var tm5 = this.m[5];
  1905. var tm6 = this.m[6];
  1906. var tm7 = this.m[7];
  1907. var tm8 = this.m[8];
  1908. var tm9 = this.m[9];
  1909. var tm10 = this.m[10];
  1910. var tm11 = this.m[11];
  1911. var tm12 = this.m[12];
  1912. var tm13 = this.m[13];
  1913. var tm14 = this.m[14];
  1914. var tm15 = this.m[15];
  1915. var om0 = other.m[0];
  1916. var om1 = other.m[1];
  1917. var om2 = other.m[2];
  1918. var om3 = other.m[3];
  1919. var om4 = other.m[4];
  1920. var om5 = other.m[5];
  1921. var om6 = other.m[6];
  1922. var om7 = other.m[7];
  1923. var om8 = other.m[8];
  1924. var om9 = other.m[9];
  1925. var om10 = other.m[10];
  1926. var om11 = other.m[11];
  1927. var om12 = other.m[12];
  1928. var om13 = other.m[13];
  1929. var om14 = other.m[14];
  1930. var om15 = other.m[15];
  1931. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1932. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1933. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1934. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1935. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1936. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1937. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1938. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1939. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1940. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1941. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1942. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1943. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1944. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1945. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1946. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1947. return this;
  1948. };
  1949. Matrix.prototype.equals = function (value) {
  1950. return value &&
  1951. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1952. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1953. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1954. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1955. };
  1956. Matrix.prototype.clone = function () {
  1957. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1958. };
  1959. Matrix.prototype.getClassName = function () {
  1960. return "Matrix";
  1961. };
  1962. Matrix.prototype.getHashCode = function () {
  1963. var hash = this.m[0] || 0;
  1964. for (var i = 1; i < 16; i++) {
  1965. hash = (hash * 397) ^ (this.m[i] || 0);
  1966. }
  1967. return hash;
  1968. };
  1969. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1970. translation.x = this.m[12];
  1971. translation.y = this.m[13];
  1972. translation.z = this.m[14];
  1973. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1974. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1975. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1976. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1977. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1978. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1979. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1980. rotation.x = 0;
  1981. rotation.y = 0;
  1982. rotation.z = 0;
  1983. rotation.w = 1;
  1984. return false;
  1985. }
  1986. 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);
  1987. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1988. return true;
  1989. };
  1990. // Statics
  1991. Matrix.FromArray = function (array, offset) {
  1992. var result = new Matrix();
  1993. if (!offset) {
  1994. offset = 0;
  1995. }
  1996. Matrix.FromArrayToRef(array, offset, result);
  1997. return result;
  1998. };
  1999. Matrix.FromArrayToRef = function (array, offset, result) {
  2000. for (var index = 0; index < 16; index++) {
  2001. result.m[index] = array[index + offset];
  2002. }
  2003. };
  2004. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2005. for (var index = 0; index < 16; index++) {
  2006. result.m[index] = array[index + offset] * scale;
  2007. }
  2008. };
  2009. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2010. result.m[0] = initialM11;
  2011. result.m[1] = initialM12;
  2012. result.m[2] = initialM13;
  2013. result.m[3] = initialM14;
  2014. result.m[4] = initialM21;
  2015. result.m[5] = initialM22;
  2016. result.m[6] = initialM23;
  2017. result.m[7] = initialM24;
  2018. result.m[8] = initialM31;
  2019. result.m[9] = initialM32;
  2020. result.m[10] = initialM33;
  2021. result.m[11] = initialM34;
  2022. result.m[12] = initialM41;
  2023. result.m[13] = initialM42;
  2024. result.m[14] = initialM43;
  2025. result.m[15] = initialM44;
  2026. };
  2027. Matrix.prototype.getRow = function (index) {
  2028. if (index < 0 || index > 3) {
  2029. return null;
  2030. }
  2031. var i = index * 4;
  2032. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2033. };
  2034. Matrix.prototype.setRow = function (index, row) {
  2035. if (index < 0 || index > 3) {
  2036. return this;
  2037. }
  2038. var i = index * 4;
  2039. this.m[i + 0] = row.x;
  2040. this.m[i + 1] = row.y;
  2041. this.m[i + 2] = row.z;
  2042. this.m[i + 3] = row.w;
  2043. return this;
  2044. };
  2045. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2046. var result = new Matrix();
  2047. result.m[0] = initialM11;
  2048. result.m[1] = initialM12;
  2049. result.m[2] = initialM13;
  2050. result.m[3] = initialM14;
  2051. result.m[4] = initialM21;
  2052. result.m[5] = initialM22;
  2053. result.m[6] = initialM23;
  2054. result.m[7] = initialM24;
  2055. result.m[8] = initialM31;
  2056. result.m[9] = initialM32;
  2057. result.m[10] = initialM33;
  2058. result.m[11] = initialM34;
  2059. result.m[12] = initialM41;
  2060. result.m[13] = initialM42;
  2061. result.m[14] = initialM43;
  2062. result.m[15] = initialM44;
  2063. return result;
  2064. };
  2065. Matrix.Compose = function (scale, rotation, translation) {
  2066. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2067. var rotationMatrix = Matrix.Identity();
  2068. rotation.toRotationMatrix(rotationMatrix);
  2069. result = result.multiply(rotationMatrix);
  2070. result.setTranslation(translation);
  2071. return result;
  2072. };
  2073. Matrix.Identity = function () {
  2074. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2075. };
  2076. Matrix.IdentityToRef = function (result) {
  2077. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2078. };
  2079. Matrix.Zero = function () {
  2080. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2081. };
  2082. Matrix.RotationX = function (angle) {
  2083. var result = new Matrix();
  2084. Matrix.RotationXToRef(angle, result);
  2085. return result;
  2086. };
  2087. Matrix.Invert = function (source) {
  2088. var result = new Matrix();
  2089. source.invertToRef(result);
  2090. return result;
  2091. };
  2092. Matrix.RotationXToRef = function (angle, result) {
  2093. var s = Math.sin(angle);
  2094. var c = Math.cos(angle);
  2095. result.m[0] = 1.0;
  2096. result.m[15] = 1.0;
  2097. result.m[5] = c;
  2098. result.m[10] = c;
  2099. result.m[9] = -s;
  2100. result.m[6] = s;
  2101. result.m[1] = 0;
  2102. result.m[2] = 0;
  2103. result.m[3] = 0;
  2104. result.m[4] = 0;
  2105. result.m[7] = 0;
  2106. result.m[8] = 0;
  2107. result.m[11] = 0;
  2108. result.m[12] = 0;
  2109. result.m[13] = 0;
  2110. result.m[14] = 0;
  2111. };
  2112. Matrix.RotationY = function (angle) {
  2113. var result = new Matrix();
  2114. Matrix.RotationYToRef(angle, result);
  2115. return result;
  2116. };
  2117. Matrix.RotationYToRef = function (angle, result) {
  2118. var s = Math.sin(angle);
  2119. var c = Math.cos(angle);
  2120. result.m[5] = 1.0;
  2121. result.m[15] = 1.0;
  2122. result.m[0] = c;
  2123. result.m[2] = -s;
  2124. result.m[8] = s;
  2125. result.m[10] = c;
  2126. result.m[1] = 0;
  2127. result.m[3] = 0;
  2128. result.m[4] = 0;
  2129. result.m[6] = 0;
  2130. result.m[7] = 0;
  2131. result.m[9] = 0;
  2132. result.m[11] = 0;
  2133. result.m[12] = 0;
  2134. result.m[13] = 0;
  2135. result.m[14] = 0;
  2136. };
  2137. Matrix.RotationZ = function (angle) {
  2138. var result = new Matrix();
  2139. Matrix.RotationZToRef(angle, result);
  2140. return result;
  2141. };
  2142. Matrix.RotationZToRef = function (angle, result) {
  2143. var s = Math.sin(angle);
  2144. var c = Math.cos(angle);
  2145. result.m[10] = 1.0;
  2146. result.m[15] = 1.0;
  2147. result.m[0] = c;
  2148. result.m[1] = s;
  2149. result.m[4] = -s;
  2150. result.m[5] = c;
  2151. result.m[2] = 0;
  2152. result.m[3] = 0;
  2153. result.m[6] = 0;
  2154. result.m[7] = 0;
  2155. result.m[8] = 0;
  2156. result.m[9] = 0;
  2157. result.m[11] = 0;
  2158. result.m[12] = 0;
  2159. result.m[13] = 0;
  2160. result.m[14] = 0;
  2161. };
  2162. Matrix.RotationAxis = function (axis, angle) {
  2163. var result = Matrix.Zero();
  2164. Matrix.RotationAxisToRef(axis, angle, result);
  2165. return result;
  2166. };
  2167. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2168. var s = Math.sin(-angle);
  2169. var c = Math.cos(-angle);
  2170. var c1 = 1 - c;
  2171. axis.normalize();
  2172. result.m[0] = (axis.x * axis.x) * c1 + c;
  2173. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2174. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2175. result.m[3] = 0.0;
  2176. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2177. result.m[5] = (axis.y * axis.y) * c1 + c;
  2178. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2179. result.m[7] = 0.0;
  2180. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2181. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2182. result.m[10] = (axis.z * axis.z) * c1 + c;
  2183. result.m[11] = 0.0;
  2184. result.m[15] = 1.0;
  2185. };
  2186. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2187. var result = new Matrix();
  2188. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2189. return result;
  2190. };
  2191. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2192. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2193. this._tempQuaternion.toRotationMatrix(result);
  2194. };
  2195. Matrix.Scaling = function (x, y, z) {
  2196. var result = Matrix.Zero();
  2197. Matrix.ScalingToRef(x, y, z, result);
  2198. return result;
  2199. };
  2200. Matrix.ScalingToRef = function (x, y, z, result) {
  2201. result.m[0] = x;
  2202. result.m[1] = 0;
  2203. result.m[2] = 0;
  2204. result.m[3] = 0;
  2205. result.m[4] = 0;
  2206. result.m[5] = y;
  2207. result.m[6] = 0;
  2208. result.m[7] = 0;
  2209. result.m[8] = 0;
  2210. result.m[9] = 0;
  2211. result.m[10] = z;
  2212. result.m[11] = 0;
  2213. result.m[12] = 0;
  2214. result.m[13] = 0;
  2215. result.m[14] = 0;
  2216. result.m[15] = 1.0;
  2217. };
  2218. Matrix.Translation = function (x, y, z) {
  2219. var result = Matrix.Identity();
  2220. Matrix.TranslationToRef(x, y, z, result);
  2221. return result;
  2222. };
  2223. Matrix.TranslationToRef = function (x, y, z, result) {
  2224. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2225. };
  2226. Matrix.Lerp = function (startValue, endValue, gradient) {
  2227. var result = Matrix.Zero();
  2228. for (var index = 0; index < 16; index++) {
  2229. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2230. }
  2231. return result;
  2232. };
  2233. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2234. var startScale = new Vector3(0, 0, 0);
  2235. var startRotation = new Quaternion();
  2236. var startTranslation = new Vector3(0, 0, 0);
  2237. startValue.decompose(startScale, startRotation, startTranslation);
  2238. var endScale = new Vector3(0, 0, 0);
  2239. var endRotation = new Quaternion();
  2240. var endTranslation = new Vector3(0, 0, 0);
  2241. endValue.decompose(endScale, endRotation, endTranslation);
  2242. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2243. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2244. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2245. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2246. };
  2247. Matrix.LookAtLH = function (eye, target, up) {
  2248. var result = Matrix.Zero();
  2249. Matrix.LookAtLHToRef(eye, target, up, result);
  2250. return result;
  2251. };
  2252. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2253. // Z axis
  2254. target.subtractToRef(eye, this._zAxis);
  2255. this._zAxis.normalize();
  2256. // X axis
  2257. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2258. if (this._xAxis.lengthSquared() === 0) {
  2259. this._xAxis.x = 1.0;
  2260. }
  2261. else {
  2262. this._xAxis.normalize();
  2263. }
  2264. // Y axis
  2265. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2266. this._yAxis.normalize();
  2267. // Eye angles
  2268. var ex = -Vector3.Dot(this._xAxis, eye);
  2269. var ey = -Vector3.Dot(this._yAxis, eye);
  2270. var ez = -Vector3.Dot(this._zAxis, eye);
  2271. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2272. };
  2273. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2274. var matrix = Matrix.Zero();
  2275. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2276. return matrix;
  2277. };
  2278. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2279. var hw = 2.0 / width;
  2280. var hh = 2.0 / height;
  2281. var id = 1.0 / (zfar - znear);
  2282. var nid = znear / (znear - zfar);
  2283. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2284. };
  2285. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2286. var matrix = Matrix.Zero();
  2287. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2288. return matrix;
  2289. };
  2290. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2291. result.m[0] = 2.0 / (right - left);
  2292. result.m[1] = result.m[2] = result.m[3] = 0;
  2293. result.m[5] = 2.0 / (top - bottom);
  2294. result.m[4] = result.m[6] = result.m[7] = 0;
  2295. result.m[10] = -1.0 / (znear - zfar);
  2296. result.m[8] = result.m[9] = result.m[11] = 0;
  2297. result.m[12] = (left + right) / (left - right);
  2298. result.m[13] = (top + bottom) / (bottom - top);
  2299. result.m[14] = znear / (znear - zfar);
  2300. result.m[15] = 1.0;
  2301. };
  2302. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2303. var matrix = Matrix.Zero();
  2304. matrix.m[0] = (2.0 * znear) / width;
  2305. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2306. matrix.m[5] = (2.0 * znear) / height;
  2307. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2308. matrix.m[10] = -zfar / (znear - zfar);
  2309. matrix.m[8] = matrix.m[9] = 0.0;
  2310. matrix.m[11] = 1.0;
  2311. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2312. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2313. return matrix;
  2314. };
  2315. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2316. var matrix = Matrix.Zero();
  2317. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2318. return matrix;
  2319. };
  2320. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2321. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2322. var tan = 1.0 / (Math.tan(fov * 0.5));
  2323. if (isVerticalFovFixed) {
  2324. result.m[0] = tan / aspect;
  2325. }
  2326. else {
  2327. result.m[0] = tan;
  2328. }
  2329. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2330. if (isVerticalFovFixed) {
  2331. result.m[5] = tan;
  2332. }
  2333. else {
  2334. result.m[5] = tan * aspect;
  2335. }
  2336. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2337. result.m[8] = result.m[9] = 0.0;
  2338. result.m[10] = -zfar / (znear - zfar);
  2339. result.m[11] = 1.0;
  2340. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2341. result.m[14] = (znear * zfar) / (znear - zfar);
  2342. };
  2343. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2344. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2345. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2346. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2347. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2348. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2349. var xScale = 2.0 / (leftTan + rightTan);
  2350. var yScale = 2.0 / (upTan + downTan);
  2351. result.m[0] = xScale;
  2352. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2353. result.m[5] = yScale;
  2354. result.m[6] = result.m[7] = 0.0;
  2355. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2356. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2357. //result.m[10] = -(znear + zfar) / (zfar - znear);
  2358. result.m[10] = -zfar / (znear - zfar);
  2359. result.m[11] = 1.0;
  2360. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2361. //result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2362. result.m[14] = (znear * zfar) / (znear - zfar);
  2363. };
  2364. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2365. var cw = viewport.width;
  2366. var ch = viewport.height;
  2367. var cx = viewport.x;
  2368. var cy = viewport.y;
  2369. 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);
  2370. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2371. };
  2372. Matrix.GetAsMatrix2x2 = function (matrix) {
  2373. return new Float32Array([
  2374. matrix.m[0], matrix.m[1],
  2375. matrix.m[4], matrix.m[5]
  2376. ]);
  2377. };
  2378. Matrix.GetAsMatrix3x3 = function (matrix) {
  2379. return new Float32Array([
  2380. matrix.m[0], matrix.m[1], matrix.m[2],
  2381. matrix.m[4], matrix.m[5], matrix.m[6],
  2382. matrix.m[8], matrix.m[9], matrix.m[10]
  2383. ]);
  2384. };
  2385. Matrix.Transpose = function (matrix) {
  2386. var result = new Matrix();
  2387. result.m[0] = matrix.m[0];
  2388. result.m[1] = matrix.m[4];
  2389. result.m[2] = matrix.m[8];
  2390. result.m[3] = matrix.m[12];
  2391. result.m[4] = matrix.m[1];
  2392. result.m[5] = matrix.m[5];
  2393. result.m[6] = matrix.m[9];
  2394. result.m[7] = matrix.m[13];
  2395. result.m[8] = matrix.m[2];
  2396. result.m[9] = matrix.m[6];
  2397. result.m[10] = matrix.m[10];
  2398. result.m[11] = matrix.m[14];
  2399. result.m[12] = matrix.m[3];
  2400. result.m[13] = matrix.m[7];
  2401. result.m[14] = matrix.m[11];
  2402. result.m[15] = matrix.m[15];
  2403. return result;
  2404. };
  2405. Matrix.Reflection = function (plane) {
  2406. var matrix = new Matrix();
  2407. Matrix.ReflectionToRef(plane, matrix);
  2408. return matrix;
  2409. };
  2410. Matrix.ReflectionToRef = function (plane, result) {
  2411. plane.normalize();
  2412. var x = plane.normal.x;
  2413. var y = plane.normal.y;
  2414. var z = plane.normal.z;
  2415. var temp = -2 * x;
  2416. var temp2 = -2 * y;
  2417. var temp3 = -2 * z;
  2418. result.m[0] = (temp * x) + 1;
  2419. result.m[1] = temp2 * x;
  2420. result.m[2] = temp3 * x;
  2421. result.m[3] = 0.0;
  2422. result.m[4] = temp * y;
  2423. result.m[5] = (temp2 * y) + 1;
  2424. result.m[6] = temp3 * y;
  2425. result.m[7] = 0.0;
  2426. result.m[8] = temp * z;
  2427. result.m[9] = temp2 * z;
  2428. result.m[10] = (temp3 * z) + 1;
  2429. result.m[11] = 0.0;
  2430. result.m[12] = temp * plane.d;
  2431. result.m[13] = temp2 * plane.d;
  2432. result.m[14] = temp3 * plane.d;
  2433. result.m[15] = 1.0;
  2434. };
  2435. Matrix._tempQuaternion = new Quaternion();
  2436. Matrix._xAxis = Vector3.Zero();
  2437. Matrix._yAxis = Vector3.Zero();
  2438. Matrix._zAxis = Vector3.Zero();
  2439. return Matrix;
  2440. }());
  2441. BABYLON.Matrix = Matrix;
  2442. var Plane = (function () {
  2443. function Plane(a, b, c, d) {
  2444. this.normal = new Vector3(a, b, c);
  2445. this.d = d;
  2446. }
  2447. Plane.prototype.asArray = function () {
  2448. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2449. };
  2450. // Methods
  2451. Plane.prototype.clone = function () {
  2452. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2453. };
  2454. Plane.prototype.getClassName = function () {
  2455. return "Plane";
  2456. };
  2457. Plane.prototype.getHashCode = function () {
  2458. var hash = this.normal.getHashCode();
  2459. hash = (hash * 397) ^ (this.d || 0);
  2460. return hash;
  2461. };
  2462. Plane.prototype.normalize = function () {
  2463. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2464. var magnitude = 0;
  2465. if (norm !== 0) {
  2466. magnitude = 1.0 / norm;
  2467. }
  2468. this.normal.x *= magnitude;
  2469. this.normal.y *= magnitude;
  2470. this.normal.z *= magnitude;
  2471. this.d *= magnitude;
  2472. return this;
  2473. };
  2474. Plane.prototype.transform = function (transformation) {
  2475. var transposedMatrix = Matrix.Transpose(transformation);
  2476. var x = this.normal.x;
  2477. var y = this.normal.y;
  2478. var z = this.normal.z;
  2479. var d = this.d;
  2480. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2481. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2482. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2483. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2484. return new Plane(normalX, normalY, normalZ, finalD);
  2485. };
  2486. Plane.prototype.dotCoordinate = function (point) {
  2487. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2488. };
  2489. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2490. var x1 = point2.x - point1.x;
  2491. var y1 = point2.y - point1.y;
  2492. var z1 = point2.z - point1.z;
  2493. var x2 = point3.x - point1.x;
  2494. var y2 = point3.y - point1.y;
  2495. var z2 = point3.z - point1.z;
  2496. var yz = (y1 * z2) - (z1 * y2);
  2497. var xz = (z1 * x2) - (x1 * z2);
  2498. var xy = (x1 * y2) - (y1 * x2);
  2499. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2500. var invPyth;
  2501. if (pyth !== 0) {
  2502. invPyth = 1.0 / pyth;
  2503. }
  2504. else {
  2505. invPyth = 0;
  2506. }
  2507. this.normal.x = yz * invPyth;
  2508. this.normal.y = xz * invPyth;
  2509. this.normal.z = xy * invPyth;
  2510. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2511. return this;
  2512. };
  2513. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2514. var dot = Vector3.Dot(this.normal, direction);
  2515. return (dot <= epsilon);
  2516. };
  2517. Plane.prototype.signedDistanceTo = function (point) {
  2518. return Vector3.Dot(point, this.normal) + this.d;
  2519. };
  2520. // Statics
  2521. Plane.FromArray = function (array) {
  2522. return new Plane(array[0], array[1], array[2], array[3]);
  2523. };
  2524. Plane.FromPoints = function (point1, point2, point3) {
  2525. var result = new Plane(0, 0, 0, 0);
  2526. result.copyFromPoints(point1, point2, point3);
  2527. return result;
  2528. };
  2529. Plane.FromPositionAndNormal = function (origin, normal) {
  2530. var result = new Plane(0, 0, 0, 0);
  2531. normal.normalize();
  2532. result.normal = normal;
  2533. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2534. return result;
  2535. };
  2536. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2537. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2538. return Vector3.Dot(point, normal) + d;
  2539. };
  2540. return Plane;
  2541. }());
  2542. BABYLON.Plane = Plane;
  2543. var Viewport = (function () {
  2544. function Viewport(x, y, width, height) {
  2545. this.x = x;
  2546. this.y = y;
  2547. this.width = width;
  2548. this.height = height;
  2549. }
  2550. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2551. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2552. };
  2553. return Viewport;
  2554. }());
  2555. BABYLON.Viewport = Viewport;
  2556. var Frustum = (function () {
  2557. function Frustum() {
  2558. }
  2559. Frustum.GetPlanes = function (transform) {
  2560. var frustumPlanes = [];
  2561. for (var index = 0; index < 6; index++) {
  2562. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2563. }
  2564. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2565. return frustumPlanes;
  2566. };
  2567. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2568. // Near
  2569. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2570. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2571. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2572. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2573. frustumPlanes[0].normalize();
  2574. // Far
  2575. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2576. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2577. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2578. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2579. frustumPlanes[1].normalize();
  2580. // Left
  2581. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2582. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2583. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2584. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2585. frustumPlanes[2].normalize();
  2586. // Right
  2587. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2588. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2589. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2590. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2591. frustumPlanes[3].normalize();
  2592. // Top
  2593. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2594. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2595. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2596. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2597. frustumPlanes[4].normalize();
  2598. // Bottom
  2599. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2600. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2601. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2602. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2603. frustumPlanes[5].normalize();
  2604. };
  2605. return Frustum;
  2606. }());
  2607. BABYLON.Frustum = Frustum;
  2608. (function (Space) {
  2609. Space[Space["LOCAL"] = 0] = "LOCAL";
  2610. Space[Space["WORLD"] = 1] = "WORLD";
  2611. })(BABYLON.Space || (BABYLON.Space = {}));
  2612. var Space = BABYLON.Space;
  2613. var Axis = (function () {
  2614. function Axis() {
  2615. }
  2616. Axis.X = new Vector3(1, 0, 0);
  2617. Axis.Y = new Vector3(0, 1, 0);
  2618. Axis.Z = new Vector3(0, 0, 1);
  2619. return Axis;
  2620. }());
  2621. BABYLON.Axis = Axis;
  2622. ;
  2623. var BezierCurve = (function () {
  2624. function BezierCurve() {
  2625. }
  2626. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2627. // Extract X (which is equal to time here)
  2628. var f0 = 1 - 3 * x2 + 3 * x1;
  2629. var f1 = 3 * x2 - 6 * x1;
  2630. var f2 = 3 * x1;
  2631. var refinedT = t;
  2632. for (var i = 0; i < 5; i++) {
  2633. var refinedT2 = refinedT * refinedT;
  2634. var refinedT3 = refinedT2 * refinedT;
  2635. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2636. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2637. refinedT -= (x - t) * slope;
  2638. refinedT = Math.min(1, Math.max(0, refinedT));
  2639. }
  2640. // Resolve cubic bezier for the given x
  2641. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2642. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2643. Math.pow(refinedT, 3);
  2644. };
  2645. return BezierCurve;
  2646. }());
  2647. BABYLON.BezierCurve = BezierCurve;
  2648. (function (Orientation) {
  2649. Orientation[Orientation["CW"] = 0] = "CW";
  2650. Orientation[Orientation["CCW"] = 1] = "CCW";
  2651. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2652. var Orientation = BABYLON.Orientation;
  2653. var Angle = (function () {
  2654. function Angle(radians) {
  2655. var _this = this;
  2656. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2657. this.radians = function () { return _this._radians; };
  2658. this._radians = radians;
  2659. if (this._radians < 0)
  2660. this._radians += (2 * Math.PI);
  2661. }
  2662. Angle.BetweenTwoPoints = function (a, b) {
  2663. var delta = b.subtract(a);
  2664. var theta = Math.atan2(delta.y, delta.x);
  2665. return new Angle(theta);
  2666. };
  2667. Angle.FromRadians = function (radians) {
  2668. return new Angle(radians);
  2669. };
  2670. Angle.FromDegrees = function (degrees) {
  2671. return new Angle(degrees * Math.PI / 180);
  2672. };
  2673. return Angle;
  2674. }());
  2675. BABYLON.Angle = Angle;
  2676. var Arc2 = (function () {
  2677. function Arc2(startPoint, midPoint, endPoint) {
  2678. this.startPoint = startPoint;
  2679. this.midPoint = midPoint;
  2680. this.endPoint = endPoint;
  2681. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2682. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2683. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2684. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2685. 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);
  2686. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2687. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2688. var a1 = this.startAngle.degrees();
  2689. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2690. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2691. // angles correction
  2692. if (a2 - a1 > +180.0)
  2693. a2 -= 360.0;
  2694. if (a2 - a1 < -180.0)
  2695. a2 += 360.0;
  2696. if (a3 - a2 > +180.0)
  2697. a3 -= 360.0;
  2698. if (a3 - a2 < -180.0)
  2699. a3 += 360.0;
  2700. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2701. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2702. }
  2703. return Arc2;
  2704. }());
  2705. BABYLON.Arc2 = Arc2;
  2706. var Path2 = (function () {
  2707. function Path2(x, y) {
  2708. this._points = new Array();
  2709. this._length = 0;
  2710. this.closed = false;
  2711. this._points.push(new Vector2(x, y));
  2712. }
  2713. Path2.prototype.addLineTo = function (x, y) {
  2714. if (closed) {
  2715. //Tools.Error("cannot add lines to closed paths");
  2716. return this;
  2717. }
  2718. var newPoint = new Vector2(x, y);
  2719. var previousPoint = this._points[this._points.length - 1];
  2720. this._points.push(newPoint);
  2721. this._length += newPoint.subtract(previousPoint).length();
  2722. return this;
  2723. };
  2724. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2725. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2726. if (closed) {
  2727. //Tools.Error("cannot add arcs to closed paths");
  2728. return this;
  2729. }
  2730. var startPoint = this._points[this._points.length - 1];
  2731. var midPoint = new Vector2(midX, midY);
  2732. var endPoint = new Vector2(endX, endY);
  2733. var arc = new Arc2(startPoint, midPoint, endPoint);
  2734. var increment = arc.angle.radians() / numberOfSegments;
  2735. if (arc.orientation === Orientation.CW)
  2736. increment *= -1;
  2737. var currentAngle = arc.startAngle.radians() + increment;
  2738. for (var i = 0; i < numberOfSegments; i++) {
  2739. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2740. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2741. this.addLineTo(x, y);
  2742. currentAngle += increment;
  2743. }
  2744. return this;
  2745. };
  2746. Path2.prototype.close = function () {
  2747. this.closed = true;
  2748. return this;
  2749. };
  2750. Path2.prototype.length = function () {
  2751. var result = this._length;
  2752. if (!this.closed) {
  2753. var lastPoint = this._points[this._points.length - 1];
  2754. var firstPoint = this._points[0];
  2755. result += (firstPoint.subtract(lastPoint).length());
  2756. }
  2757. return result;
  2758. };
  2759. Path2.prototype.getPoints = function () {
  2760. return this._points;
  2761. };
  2762. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2763. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2764. //Tools.Error("normalized length position should be between 0 and 1.");
  2765. return Vector2.Zero();
  2766. }
  2767. var lengthPosition = normalizedLengthPosition * this.length();
  2768. var previousOffset = 0;
  2769. for (var i = 0; i < this._points.length; i++) {
  2770. var j = (i + 1) % this._points.length;
  2771. var a = this._points[i];
  2772. var b = this._points[j];
  2773. var bToA = b.subtract(a);
  2774. var nextOffset = (bToA.length() + previousOffset);
  2775. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2776. var dir = bToA.normalize();
  2777. var localOffset = lengthPosition - previousOffset;
  2778. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2779. }
  2780. previousOffset = nextOffset;
  2781. }
  2782. //Tools.Error("internal error");
  2783. return Vector2.Zero();
  2784. };
  2785. Path2.StartingAt = function (x, y) {
  2786. return new Path2(x, y);
  2787. };
  2788. return Path2;
  2789. }());
  2790. BABYLON.Path2 = Path2;
  2791. var Path3D = (function () {
  2792. /**
  2793. * new Path3D(path, normal, raw)
  2794. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2795. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2796. * path : an array of Vector3, the curve axis of the Path3D
  2797. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2798. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2799. */
  2800. function Path3D(path, firstNormal, raw) {
  2801. this.path = path;
  2802. this._curve = new Array();
  2803. this._distances = new Array();
  2804. this._tangents = new Array();
  2805. this._normals = new Array();
  2806. this._binormals = new Array();
  2807. for (var p = 0; p < path.length; p++) {
  2808. this._curve[p] = path[p].clone(); // hard copy
  2809. }
  2810. this._raw = raw || false;
  2811. this._compute(firstNormal);
  2812. }
  2813. /**
  2814. * Returns the Path3D array of successive Vector3 designing its curve.
  2815. */
  2816. Path3D.prototype.getCurve = function () {
  2817. return this._curve;
  2818. };
  2819. /**
  2820. * Returns an array populated with tangent vectors on each Path3D curve point.
  2821. */
  2822. Path3D.prototype.getTangents = function () {
  2823. return this._tangents;
  2824. };
  2825. /**
  2826. * Returns an array populated with normal vectors on each Path3D curve point.
  2827. */
  2828. Path3D.prototype.getNormals = function () {
  2829. return this._normals;
  2830. };
  2831. /**
  2832. * Returns an array populated with binormal vectors on each Path3D curve point.
  2833. */
  2834. Path3D.prototype.getBinormals = function () {
  2835. return this._binormals;
  2836. };
  2837. /**
  2838. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2839. */
  2840. Path3D.prototype.getDistances = function () {
  2841. return this._distances;
  2842. };
  2843. /**
  2844. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2845. * Returns the same object updated.
  2846. */
  2847. Path3D.prototype.update = function (path, firstNormal) {
  2848. for (var p = 0; p < path.length; p++) {
  2849. this._curve[p].x = path[p].x;
  2850. this._curve[p].y = path[p].y;
  2851. this._curve[p].z = path[p].z;
  2852. }
  2853. this._compute(firstNormal);
  2854. return this;
  2855. };
  2856. // private function compute() : computes tangents, normals and binormals
  2857. Path3D.prototype._compute = function (firstNormal) {
  2858. var l = this._curve.length;
  2859. // first and last tangents
  2860. this._tangents[0] = this._getFirstNonNullVector(0);
  2861. if (!this._raw) {
  2862. this._tangents[0].normalize();
  2863. }
  2864. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2865. if (!this._raw) {
  2866. this._tangents[l - 1].normalize();
  2867. }
  2868. // normals and binormals at first point : arbitrary vector with _normalVector()
  2869. var tg0 = this._tangents[0];
  2870. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2871. this._normals[0] = pp0;
  2872. if (!this._raw) {
  2873. this._normals[0].normalize();
  2874. }
  2875. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2876. if (!this._raw) {
  2877. this._binormals[0].normalize();
  2878. }
  2879. this._distances[0] = 0.0;
  2880. // normals and binormals : next points
  2881. var prev; // previous vector (segment)
  2882. var cur; // current vector (segment)
  2883. var curTang; // current tangent
  2884. // previous normal
  2885. var prevBinor; // previous binormal
  2886. for (var i = 1; i < l; i++) {
  2887. // tangents
  2888. prev = this._getLastNonNullVector(i);
  2889. if (i < l - 1) {
  2890. cur = this._getFirstNonNullVector(i);
  2891. this._tangents[i] = prev.add(cur);
  2892. this._tangents[i].normalize();
  2893. }
  2894. this._distances[i] = this._distances[i - 1] + prev.length();
  2895. // normals and binormals
  2896. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2897. curTang = this._tangents[i];
  2898. prevBinor = this._binormals[i - 1];
  2899. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2900. if (!this._raw) {
  2901. this._normals[i].normalize();
  2902. }
  2903. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2904. if (!this._raw) {
  2905. this._binormals[i].normalize();
  2906. }
  2907. }
  2908. };
  2909. // private function getFirstNonNullVector(index)
  2910. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2911. Path3D.prototype._getFirstNonNullVector = function (index) {
  2912. var i = 1;
  2913. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2914. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2915. i++;
  2916. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2917. }
  2918. return nNVector;
  2919. };
  2920. // private function getLastNonNullVector(index)
  2921. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2922. Path3D.prototype._getLastNonNullVector = function (index) {
  2923. var i = 1;
  2924. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2925. while (nLVector.length() === 0 && index > i + 1) {
  2926. i++;
  2927. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2928. }
  2929. return nLVector;
  2930. };
  2931. // private function normalVector(v0, vt, va) :
  2932. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2933. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2934. Path3D.prototype._normalVector = function (v0, vt, va) {
  2935. var normal0;
  2936. var tgl = vt.length();
  2937. if (tgl === 0.0) {
  2938. tgl = 1.0;
  2939. }
  2940. if (va === undefined || va === null) {
  2941. var point;
  2942. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  2943. point = new Vector3(0.0, -1.0, 0.0);
  2944. }
  2945. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  2946. point = new Vector3(1.0, 0.0, 0.0);
  2947. }
  2948. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  2949. point = new Vector3(0.0, 0.0, 1.0);
  2950. }
  2951. normal0 = Vector3.Cross(vt, point);
  2952. }
  2953. else {
  2954. normal0 = Vector3.Cross(vt, va);
  2955. Vector3.CrossToRef(normal0, vt, normal0);
  2956. }
  2957. normal0.normalize();
  2958. return normal0;
  2959. };
  2960. return Path3D;
  2961. }());
  2962. BABYLON.Path3D = Path3D;
  2963. var Curve3 = (function () {
  2964. /**
  2965. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  2966. * A Curve3 is designed from a series of successive Vector3.
  2967. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  2968. */
  2969. function Curve3(points) {
  2970. this._length = 0.0;
  2971. this._points = points;
  2972. this._length = this._computeLength(points);
  2973. }
  2974. /**
  2975. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  2976. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  2977. * @param v1 (Vector3) the control point
  2978. * @param v2 (Vector3) the end point of the Quadratic Bezier
  2979. * @param nbPoints (integer) the wanted number of points in the curve
  2980. */
  2981. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2982. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2983. var bez = new Array();
  2984. var equation = function (t, val0, val1, val2) {
  2985. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  2986. return res;
  2987. };
  2988. for (var i = 0; i <= nbPoints; i++) {
  2989. 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)));
  2990. }
  2991. return new Curve3(bez);
  2992. };
  2993. /**
  2994. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  2995. * @param v0 (Vector3) the origin point of the Cubic Bezier
  2996. * @param v1 (Vector3) the first control point
  2997. * @param v2 (Vector3) the second control point
  2998. * @param v3 (Vector3) the end point of the Cubic Bezier
  2999. * @param nbPoints (integer) the wanted number of points in the curve
  3000. */
  3001. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3002. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3003. var bez = new Array();
  3004. var equation = function (t, val0, val1, val2, val3) {
  3005. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  3006. return res;
  3007. };
  3008. for (var i = 0; i <= nbPoints; i++) {
  3009. 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)));
  3010. }
  3011. return new Curve3(bez);
  3012. };
  3013. /**
  3014. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3015. * @param p1 (Vector3) the origin point of the Hermite Spline
  3016. * @param t1 (Vector3) the tangent vector at the origin point
  3017. * @param p2 (Vector3) the end point of the Hermite Spline
  3018. * @param t2 (Vector3) the tangent vector at the end point
  3019. * @param nbPoints (integer) the wanted number of points in the curve
  3020. */
  3021. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3022. var hermite = new Array();
  3023. var step = 1.0 / nbPoints;
  3024. for (var i = 0; i <= nbPoints; i++) {
  3025. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3026. }
  3027. return new Curve3(hermite);
  3028. };
  3029. /**
  3030. * Returns the Curve3 stored array of successive Vector3
  3031. */
  3032. Curve3.prototype.getPoints = function () {
  3033. return this._points;
  3034. };
  3035. /**
  3036. * Returns the computed length (float) of the curve.
  3037. */
  3038. Curve3.prototype.length = function () {
  3039. return this._length;
  3040. };
  3041. /**
  3042. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3043. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3044. * curveA and curveB keep unchanged.
  3045. */
  3046. Curve3.prototype.continue = function (curve) {
  3047. var lastPoint = this._points[this._points.length - 1];
  3048. var continuedPoints = this._points.slice();
  3049. var curvePoints = curve.getPoints();
  3050. for (var i = 1; i < curvePoints.length; i++) {
  3051. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3052. }
  3053. var continuedCurve = new Curve3(continuedPoints);
  3054. return continuedCurve;
  3055. };
  3056. Curve3.prototype._computeLength = function (path) {
  3057. var l = 0;
  3058. for (var i = 1; i < path.length; i++) {
  3059. l += (path[i].subtract(path[i - 1])).length();
  3060. }
  3061. return l;
  3062. };
  3063. return Curve3;
  3064. }());
  3065. BABYLON.Curve3 = Curve3;
  3066. // SphericalHarmonics
  3067. var SphericalHarmonics = (function () {
  3068. function SphericalHarmonics() {
  3069. this.L00 = Vector3.Zero();
  3070. this.L1_1 = Vector3.Zero();
  3071. this.L10 = Vector3.Zero();
  3072. this.L11 = Vector3.Zero();
  3073. this.L2_2 = Vector3.Zero();
  3074. this.L2_1 = Vector3.Zero();
  3075. this.L20 = Vector3.Zero();
  3076. this.L21 = Vector3.Zero();
  3077. this.L22 = Vector3.Zero();
  3078. }
  3079. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3080. var colorVector = new Vector3(color.r, color.g, color.b);
  3081. var c = colorVector.scale(deltaSolidAngle);
  3082. this.L00 = this.L00.add(c.scale(0.282095));
  3083. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3084. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3085. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3086. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3087. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3088. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3089. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3090. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3091. };
  3092. SphericalHarmonics.prototype.scale = function (scale) {
  3093. this.L00 = this.L00.scale(scale);
  3094. this.L1_1 = this.L1_1.scale(scale);
  3095. this.L10 = this.L10.scale(scale);
  3096. this.L11 = this.L11.scale(scale);
  3097. this.L2_2 = this.L2_2.scale(scale);
  3098. this.L2_1 = this.L2_1.scale(scale);
  3099. this.L20 = this.L20.scale(scale);
  3100. this.L21 = this.L21.scale(scale);
  3101. this.L22 = this.L22.scale(scale);
  3102. };
  3103. return SphericalHarmonics;
  3104. }());
  3105. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3106. // SphericalPolynomial
  3107. var SphericalPolynomial = (function () {
  3108. function SphericalPolynomial() {
  3109. this.x = Vector3.Zero();
  3110. this.y = Vector3.Zero();
  3111. this.z = Vector3.Zero();
  3112. this.xx = Vector3.Zero();
  3113. this.yy = Vector3.Zero();
  3114. this.zz = Vector3.Zero();
  3115. this.xy = Vector3.Zero();
  3116. this.yz = Vector3.Zero();
  3117. this.zx = Vector3.Zero();
  3118. }
  3119. SphericalPolynomial.prototype.addAmbient = function (color) {
  3120. var colorVector = new Vector3(color.r, color.g, color.b);
  3121. this.xx = this.xx.add(colorVector);
  3122. this.yy = this.yy.add(colorVector);
  3123. this.zz = this.zz.add(colorVector);
  3124. };
  3125. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3126. var result = new SphericalPolynomial();
  3127. result.x = harmonics.L11.scale(1.02333);
  3128. result.y = harmonics.L1_1.scale(1.02333);
  3129. result.z = harmonics.L10.scale(1.02333);
  3130. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3131. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3132. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3133. result.yz = harmonics.L2_1.scale(0.858086);
  3134. result.zx = harmonics.L21.scale(0.858086);
  3135. result.xy = harmonics.L2_2.scale(0.858086);
  3136. return result;
  3137. };
  3138. return SphericalPolynomial;
  3139. }());
  3140. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3141. // Vertex formats
  3142. var PositionNormalVertex = (function () {
  3143. function PositionNormalVertex(position, normal) {
  3144. if (position === void 0) { position = Vector3.Zero(); }
  3145. if (normal === void 0) { normal = Vector3.Up(); }
  3146. this.position = position;
  3147. this.normal = normal;
  3148. }
  3149. PositionNormalVertex.prototype.clone = function () {
  3150. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3151. };
  3152. return PositionNormalVertex;
  3153. }());
  3154. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3155. var PositionNormalTextureVertex = (function () {
  3156. function PositionNormalTextureVertex(position, normal, uv) {
  3157. if (position === void 0) { position = Vector3.Zero(); }
  3158. if (normal === void 0) { normal = Vector3.Up(); }
  3159. if (uv === void 0) { uv = Vector2.Zero(); }
  3160. this.position = position;
  3161. this.normal = normal;
  3162. this.uv = uv;
  3163. }
  3164. PositionNormalTextureVertex.prototype.clone = function () {
  3165. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3166. };
  3167. return PositionNormalTextureVertex;
  3168. }());
  3169. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3170. // Temporary pre-allocated objects for engine internal use
  3171. // usage in any internal function :
  3172. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3173. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3174. var Tmp = (function () {
  3175. function Tmp() {
  3176. }
  3177. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3178. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3179. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3180. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3181. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3182. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3183. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3184. Matrix.Zero(), Matrix.Zero(),
  3185. Matrix.Zero(), Matrix.Zero(),
  3186. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3187. return Tmp;
  3188. }());
  3189. BABYLON.Tmp = Tmp;
  3190. })(BABYLON || (BABYLON = {}));
  3191. var BABYLON;
  3192. (function (BABYLON) {
  3193. function generateSerializableMember(type, sourceName) {
  3194. return function (target, propertyKey) {
  3195. if (!target.__serializableMembers) {
  3196. target.__serializableMembers = {};
  3197. }
  3198. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3199. };
  3200. }
  3201. function serialize(sourceName) {
  3202. return generateSerializableMember(0, sourceName); // value member
  3203. }
  3204. BABYLON.serialize = serialize;
  3205. function serializeAsTexture(sourceName) {
  3206. return generateSerializableMember(1, sourceName); // texture member
  3207. }
  3208. BABYLON.serializeAsTexture = serializeAsTexture;
  3209. function serializeAsColor3(sourceName) {
  3210. return generateSerializableMember(2, sourceName); // color3 member
  3211. }
  3212. BABYLON.serializeAsColor3 = serializeAsColor3;
  3213. function serializeAsFresnelParameters(sourceName) {
  3214. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3215. }
  3216. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3217. function serializeAsVector2(sourceName) {
  3218. return generateSerializableMember(4, sourceName); // vector2 member
  3219. }
  3220. BABYLON.serializeAsVector2 = serializeAsVector2;
  3221. function serializeAsVector3(sourceName) {
  3222. return generateSerializableMember(5, sourceName); // vector3 member
  3223. }
  3224. BABYLON.serializeAsVector3 = serializeAsVector3;
  3225. function serializeAsMeshReference(sourceName) {
  3226. return generateSerializableMember(6, sourceName); // mesh reference member
  3227. }
  3228. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3229. function serializeAsColorCurves(sourceName) {
  3230. return generateSerializableMember(7, sourceName); // color curves
  3231. }
  3232. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3233. var SerializationHelper = (function () {
  3234. function SerializationHelper() {
  3235. }
  3236. SerializationHelper.Serialize = function (entity, serializationObject) {
  3237. if (!serializationObject) {
  3238. serializationObject = {};
  3239. }
  3240. // Tags
  3241. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3242. // Properties
  3243. for (var property in entity.__serializableMembers) {
  3244. var propertyDescriptor = entity.__serializableMembers[property];
  3245. var targetPropertyName = propertyDescriptor.sourceName || property;
  3246. var propertyType = propertyDescriptor.type;
  3247. var sourceProperty = entity[property];
  3248. if (sourceProperty !== undefined && sourceProperty !== null) {
  3249. switch (propertyType) {
  3250. case 0:
  3251. serializationObject[targetPropertyName] = sourceProperty;
  3252. break;
  3253. case 1:
  3254. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3255. break;
  3256. case 2:
  3257. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3258. break;
  3259. case 3:
  3260. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3261. break;
  3262. case 4:
  3263. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3264. break;
  3265. case 5:
  3266. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3267. break;
  3268. case 6:
  3269. serializationObject[targetPropertyName] = sourceProperty.id;
  3270. break;
  3271. case 7:
  3272. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3273. break;
  3274. }
  3275. }
  3276. }
  3277. return serializationObject;
  3278. };
  3279. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3280. var destination = creationFunction();
  3281. // Tags
  3282. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3283. // Properties
  3284. for (var property in destination.__serializableMembers) {
  3285. var propertyDescriptor = destination.__serializableMembers[property];
  3286. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3287. var propertyType = propertyDescriptor.type;
  3288. if (sourceProperty !== undefined && sourceProperty !== null) {
  3289. switch (propertyType) {
  3290. case 0:
  3291. destination[property] = sourceProperty;
  3292. break;
  3293. case 1:
  3294. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3295. break;
  3296. case 2:
  3297. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3298. break;
  3299. case 3:
  3300. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3301. break;
  3302. case 4:
  3303. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3304. break;
  3305. case 5:
  3306. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3307. break;
  3308. case 6:
  3309. destination[property] = scene.getLastMeshByID(sourceProperty);
  3310. break;
  3311. case 7:
  3312. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3313. break;
  3314. }
  3315. }
  3316. }
  3317. return destination;
  3318. };
  3319. SerializationHelper.Clone = function (creationFunction, source) {
  3320. var destination = creationFunction();
  3321. // Tags
  3322. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3323. // Properties
  3324. for (var property in destination.__serializableMembers) {
  3325. var propertyDescriptor = destination.__serializableMembers[property];
  3326. var sourceProperty = source[property];
  3327. var propertyType = propertyDescriptor.type;
  3328. if (sourceProperty !== undefined && sourceProperty !== null) {
  3329. switch (propertyType) {
  3330. case 0: // Value
  3331. case 6:
  3332. destination[property] = sourceProperty;
  3333. break;
  3334. case 1: // Texture
  3335. case 2: // Color3
  3336. case 3: // FresnelParameters
  3337. case 4: // Vector2
  3338. case 5: // Vector3
  3339. case 7:
  3340. destination[property] = sourceProperty.clone();
  3341. break;
  3342. }
  3343. }
  3344. }
  3345. return destination;
  3346. };
  3347. return SerializationHelper;
  3348. }());
  3349. BABYLON.SerializationHelper = SerializationHelper;
  3350. })(BABYLON || (BABYLON = {}));
  3351. var BABYLON;
  3352. (function (BABYLON) {
  3353. /**
  3354. * A class serves as a medium between the observable and its observers
  3355. */
  3356. var EventState = (function () {
  3357. /**
  3358. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3359. */
  3360. function EventState(mask, skipNextObservers) {
  3361. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3362. this.initalize(mask, skipNextObservers);
  3363. }
  3364. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3365. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3366. this.mask = mask;
  3367. this.skipNextObservers = skipNextObservers;
  3368. return this;
  3369. };
  3370. return EventState;
  3371. }());
  3372. BABYLON.EventState = EventState;
  3373. /**
  3374. * Represent an Observer registered to a given Observable object.
  3375. */
  3376. var Observer = (function () {
  3377. function Observer(callback, mask) {
  3378. this.callback = callback;
  3379. this.mask = mask;
  3380. }
  3381. return Observer;
  3382. }());
  3383. BABYLON.Observer = Observer;
  3384. /**
  3385. * The Observable class is a simple implementation of the Observable pattern.
  3386. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  3387. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3388. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  3389. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  3390. */
  3391. var Observable = (function () {
  3392. function Observable() {
  3393. this._observers = new Array();
  3394. }
  3395. /**
  3396. * Create a new Observer with the specified callback
  3397. * @param callback the callback that will be executed for that Observer
  3398. * @param mask the mask used to filter observers
  3399. * @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.
  3400. */
  3401. Observable.prototype.add = function (callback, mask, insertFirst) {
  3402. if (mask === void 0) { mask = -1; }
  3403. if (insertFirst === void 0) { insertFirst = false; }
  3404. if (!callback) {
  3405. return null;
  3406. }
  3407. var observer = new Observer(callback, mask);
  3408. if (insertFirst) {
  3409. this._observers.unshift(observer);
  3410. }
  3411. else {
  3412. this._observers.push(observer);
  3413. }
  3414. return observer;
  3415. };
  3416. /**
  3417. * Remove an Observer from the Observable object
  3418. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3419. */
  3420. Observable.prototype.remove = function (observer) {
  3421. var index = this._observers.indexOf(observer);
  3422. if (index !== -1) {
  3423. this._observers.splice(index, 1);
  3424. return true;
  3425. }
  3426. return false;
  3427. };
  3428. /**
  3429. * Remove a callback from the Observable object
  3430. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3431. */
  3432. Observable.prototype.removeCallback = function (callback) {
  3433. for (var index = 0; index < this._observers.length; index++) {
  3434. if (this._observers[index].callback === callback) {
  3435. this._observers.splice(index, 1);
  3436. return true;
  3437. }
  3438. }
  3439. return false;
  3440. };
  3441. /**
  3442. * Notify all Observers by calling their respective callback with the given data
  3443. * @param eventData
  3444. * @param mask
  3445. */
  3446. Observable.prototype.notifyObservers = function (eventData, mask) {
  3447. if (mask === void 0) { mask = -1; }
  3448. var state = Observable._pooledEventState ? Observable._pooledEventState.initalize(mask) : new EventState(mask);
  3449. Observable._pooledEventState = null;
  3450. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3451. var obs = _a[_i];
  3452. if (obs.mask & mask) {
  3453. obs.callback(eventData, state);
  3454. }
  3455. if (state.skipNextObservers) {
  3456. break;
  3457. }
  3458. }
  3459. Observable._pooledEventState = state;
  3460. };
  3461. /**
  3462. * return true is the Observable has at least one Observer registered
  3463. */
  3464. Observable.prototype.hasObservers = function () {
  3465. return this._observers.length > 0;
  3466. };
  3467. /**
  3468. * Clear the list of observers
  3469. */
  3470. Observable.prototype.clear = function () {
  3471. this._observers = new Array();
  3472. };
  3473. /**
  3474. * Clone the current observable
  3475. */
  3476. Observable.prototype.clone = function () {
  3477. var result = new Observable();
  3478. result._observers = this._observers.slice(0);
  3479. return result;
  3480. };
  3481. Observable._pooledEventState = null;
  3482. return Observable;
  3483. }());
  3484. BABYLON.Observable = Observable;
  3485. })(BABYLON || (BABYLON = {}));
  3486. var BABYLON;
  3487. (function (BABYLON) {
  3488. var Database = (function () {
  3489. function Database(urlToScene, callbackManifestChecked) {
  3490. // Handling various flavors of prefixed version of IndexedDB
  3491. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3492. this.callbackManifestChecked = callbackManifestChecked;
  3493. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3494. this.db = null;
  3495. this.enableSceneOffline = false;
  3496. this.enableTexturesOffline = false;
  3497. this.manifestVersionFound = 0;
  3498. this.mustUpdateRessources = false;
  3499. this.hasReachedQuota = false;
  3500. if (!Database.IDBStorageEnabled) {
  3501. this.callbackManifestChecked(true);
  3502. }
  3503. else {
  3504. this.checkManifestFile();
  3505. }
  3506. }
  3507. Database.prototype.checkManifestFile = function () {
  3508. var _this = this;
  3509. function noManifestFile() {
  3510. that.enableSceneOffline = false;
  3511. that.enableTexturesOffline = false;
  3512. that.callbackManifestChecked(false);
  3513. }
  3514. var that = this;
  3515. var timeStampUsed = false;
  3516. var manifestURL = this.currentSceneUrl + ".manifest";
  3517. var xhr = new XMLHttpRequest();
  3518. if (navigator.onLine) {
  3519. // Adding a timestamp to by-pass browsers' cache
  3520. timeStampUsed = true;
  3521. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3522. }
  3523. xhr.open("GET", manifestURL, true);
  3524. xhr.addEventListener("load", function () {
  3525. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3526. try {
  3527. var manifestFile = JSON.parse(xhr.response);
  3528. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3529. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3530. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3531. _this.manifestVersionFound = manifestFile.version;
  3532. }
  3533. if (_this.callbackManifestChecked) {
  3534. _this.callbackManifestChecked(true);
  3535. }
  3536. }
  3537. catch (ex) {
  3538. noManifestFile();
  3539. }
  3540. }
  3541. else {
  3542. noManifestFile();
  3543. }
  3544. }, false);
  3545. xhr.addEventListener("error", function (event) {
  3546. if (timeStampUsed) {
  3547. timeStampUsed = false;
  3548. // Let's retry without the timeStamp
  3549. // It could fail when coupled with HTML5 Offline API
  3550. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3551. xhr.open("GET", retryManifestURL, true);
  3552. xhr.send();
  3553. }
  3554. else {
  3555. noManifestFile();
  3556. }
  3557. }, false);
  3558. try {
  3559. xhr.send();
  3560. }
  3561. catch (ex) {
  3562. BABYLON.Tools.Error("Error on XHR send request.");
  3563. that.callbackManifestChecked(false);
  3564. }
  3565. };
  3566. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3567. var _this = this;
  3568. function handleError() {
  3569. that.isSupported = false;
  3570. if (errorCallback)
  3571. errorCallback();
  3572. }
  3573. var that = this;
  3574. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3575. // Your browser doesn't support IndexedDB
  3576. this.isSupported = false;
  3577. if (errorCallback)
  3578. errorCallback();
  3579. }
  3580. else {
  3581. // If the DB hasn't been opened or created yet
  3582. if (!this.db) {
  3583. this.hasReachedQuota = false;
  3584. this.isSupported = true;
  3585. var request = this.idbFactory.open("babylonjs", 1);
  3586. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3587. request.onerror = function (event) {
  3588. handleError();
  3589. };
  3590. // executes when a version change transaction cannot complete due to other active transactions
  3591. request.onblocked = function (event) {
  3592. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3593. handleError();
  3594. };
  3595. // DB has been opened successfully
  3596. request.onsuccess = function (event) {
  3597. _this.db = request.result;
  3598. successCallback();
  3599. };
  3600. // Initialization of the DB. Creating Scenes & Textures stores
  3601. request.onupgradeneeded = function (event) {
  3602. _this.db = (event.target).result;
  3603. try {
  3604. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3605. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3606. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3607. }
  3608. catch (ex) {
  3609. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3610. handleError();
  3611. }
  3612. };
  3613. }
  3614. else {
  3615. if (successCallback)
  3616. successCallback();
  3617. }
  3618. }
  3619. };
  3620. Database.prototype.loadImageFromDB = function (url, image) {
  3621. var _this = this;
  3622. var completeURL = Database.ReturnFullUrlLocation(url);
  3623. var saveAndLoadImage = function () {
  3624. if (!_this.hasReachedQuota && _this.db !== null) {
  3625. // the texture is not yet in the DB, let's try to save it
  3626. _this._saveImageIntoDBAsync(completeURL, image);
  3627. }
  3628. else {
  3629. image.src = url;
  3630. }
  3631. };
  3632. if (!this.mustUpdateRessources) {
  3633. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3634. }
  3635. else {
  3636. saveAndLoadImage();
  3637. }
  3638. };
  3639. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3640. if (this.isSupported && this.db !== null) {
  3641. var texture;
  3642. var transaction = this.db.transaction(["textures"]);
  3643. transaction.onabort = function (event) {
  3644. image.src = url;
  3645. };
  3646. transaction.oncomplete = function (event) {
  3647. var blobTextureURL;
  3648. if (texture) {
  3649. var URL = window.URL || window.webkitURL;
  3650. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3651. image.onerror = function () {
  3652. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3653. image.src = url;
  3654. };
  3655. image.src = blobTextureURL;
  3656. }
  3657. else {
  3658. notInDBCallback();
  3659. }
  3660. };
  3661. var getRequest = transaction.objectStore("textures").get(url);
  3662. getRequest.onsuccess = function (event) {
  3663. texture = (event.target).result;
  3664. };
  3665. getRequest.onerror = function (event) {
  3666. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3667. image.src = url;
  3668. };
  3669. }
  3670. else {
  3671. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3672. image.src = url;
  3673. }
  3674. };
  3675. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3676. var _this = this;
  3677. if (this.isSupported) {
  3678. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3679. var generateBlobUrl = function () {
  3680. var blobTextureURL;
  3681. if (blob) {
  3682. var URL = window.URL || window.webkitURL;
  3683. try {
  3684. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3685. }
  3686. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3687. catch (ex) {
  3688. blobTextureURL = URL.createObjectURL(blob);
  3689. }
  3690. }
  3691. image.src = blobTextureURL;
  3692. };
  3693. if (Database.IsUASupportingBlobStorage) {
  3694. var xhr = new XMLHttpRequest(), blob;
  3695. xhr.open("GET", url, true);
  3696. xhr.responseType = "blob";
  3697. xhr.addEventListener("load", function () {
  3698. if (xhr.status === 200) {
  3699. // Blob as response (XHR2)
  3700. blob = xhr.response;
  3701. var transaction = _this.db.transaction(["textures"], "readwrite");
  3702. // the transaction could abort because of a QuotaExceededError error
  3703. transaction.onabort = function (event) {
  3704. try {
  3705. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3706. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3707. this.hasReachedQuota = true;
  3708. }
  3709. }
  3710. catch (ex) { }
  3711. generateBlobUrl();
  3712. };
  3713. transaction.oncomplete = function (event) {
  3714. generateBlobUrl();
  3715. };
  3716. var newTexture = { textureUrl: url, data: blob };
  3717. try {
  3718. // Put the blob into the dabase
  3719. var addRequest = transaction.objectStore("textures").put(newTexture);
  3720. addRequest.onsuccess = function (event) {
  3721. };
  3722. addRequest.onerror = function (event) {
  3723. generateBlobUrl();
  3724. };
  3725. }
  3726. catch (ex) {
  3727. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3728. if (ex.code === 25) {
  3729. Database.IsUASupportingBlobStorage = false;
  3730. }
  3731. image.src = url;
  3732. }
  3733. }
  3734. else {
  3735. image.src = url;
  3736. }
  3737. }, false);
  3738. xhr.addEventListener("error", function (event) {
  3739. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3740. image.src = url;
  3741. }, false);
  3742. xhr.send();
  3743. }
  3744. else {
  3745. image.src = url;
  3746. }
  3747. }
  3748. else {
  3749. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3750. image.src = url;
  3751. }
  3752. };
  3753. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3754. var _this = this;
  3755. var updateVersion = function (event) {
  3756. // the version is not yet in the DB or we need to update it
  3757. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3758. };
  3759. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3760. };
  3761. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3762. var _this = this;
  3763. if (this.isSupported) {
  3764. var version;
  3765. try {
  3766. var transaction = this.db.transaction(["versions"]);
  3767. transaction.oncomplete = function (event) {
  3768. if (version) {
  3769. // If the version in the JSON file is > than the version in DB
  3770. if (_this.manifestVersionFound > version.data) {
  3771. _this.mustUpdateRessources = true;
  3772. updateInDBCallback();
  3773. }
  3774. else {
  3775. callback(version.data);
  3776. }
  3777. }
  3778. else {
  3779. _this.mustUpdateRessources = true;
  3780. updateInDBCallback();
  3781. }
  3782. };
  3783. transaction.onabort = function (event) {
  3784. callback(-1);
  3785. };
  3786. var getRequest = transaction.objectStore("versions").get(url);
  3787. getRequest.onsuccess = function (event) {
  3788. version = (event.target).result;
  3789. };
  3790. getRequest.onerror = function (event) {
  3791. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3792. callback(-1);
  3793. };
  3794. }
  3795. catch (ex) {
  3796. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3797. callback(-1);
  3798. }
  3799. }
  3800. else {
  3801. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3802. callback(-1);
  3803. }
  3804. };
  3805. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3806. var _this = this;
  3807. if (this.isSupported && !this.hasReachedQuota) {
  3808. try {
  3809. // Open a transaction to the database
  3810. var transaction = this.db.transaction(["versions"], "readwrite");
  3811. // the transaction could abort because of a QuotaExceededError error
  3812. transaction.onabort = function (event) {
  3813. try {
  3814. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3815. _this.hasReachedQuota = true;
  3816. }
  3817. }
  3818. catch (ex) { }
  3819. callback(-1);
  3820. };
  3821. transaction.oncomplete = function (event) {
  3822. callback(_this.manifestVersionFound);
  3823. };
  3824. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3825. // Put the scene into the database
  3826. var addRequest = transaction.objectStore("versions").put(newVersion);
  3827. addRequest.onsuccess = function (event) {
  3828. };
  3829. addRequest.onerror = function (event) {
  3830. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3831. };
  3832. }
  3833. catch (ex) {
  3834. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3835. callback(-1);
  3836. }
  3837. }
  3838. else {
  3839. callback(-1);
  3840. }
  3841. };
  3842. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3843. var _this = this;
  3844. var completeUrl = Database.ReturnFullUrlLocation(url);
  3845. var saveAndLoadFile = function (event) {
  3846. // the scene is not yet in the DB, let's try to save it
  3847. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3848. };
  3849. this._checkVersionFromDB(completeUrl, function (version) {
  3850. if (version !== -1) {
  3851. if (!_this.mustUpdateRessources) {
  3852. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3853. }
  3854. else {
  3855. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3856. }
  3857. }
  3858. else {
  3859. errorCallback();
  3860. }
  3861. });
  3862. };
  3863. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3864. if (this.isSupported) {
  3865. var targetStore;
  3866. if (url.indexOf(".babylon") !== -1) {
  3867. targetStore = "scenes";
  3868. }
  3869. else {
  3870. targetStore = "textures";
  3871. }
  3872. var file;
  3873. var transaction = this.db.transaction([targetStore]);
  3874. transaction.oncomplete = function (event) {
  3875. if (file) {
  3876. callback(file.data);
  3877. }
  3878. else {
  3879. notInDBCallback();
  3880. }
  3881. };
  3882. transaction.onabort = function (event) {
  3883. notInDBCallback();
  3884. };
  3885. var getRequest = transaction.objectStore(targetStore).get(url);
  3886. getRequest.onsuccess = function (event) {
  3887. file = (event.target).result;
  3888. };
  3889. getRequest.onerror = function (event) {
  3890. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3891. notInDBCallback();
  3892. };
  3893. }
  3894. else {
  3895. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3896. callback();
  3897. }
  3898. };
  3899. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3900. var _this = this;
  3901. if (this.isSupported) {
  3902. var targetStore;
  3903. if (url.indexOf(".babylon") !== -1) {
  3904. targetStore = "scenes";
  3905. }
  3906. else {
  3907. targetStore = "textures";
  3908. }
  3909. // Create XHR
  3910. var xhr = new XMLHttpRequest(), fileData;
  3911. xhr.open("GET", url, true);
  3912. if (useArrayBuffer) {
  3913. xhr.responseType = "arraybuffer";
  3914. }
  3915. xhr.onprogress = progressCallback;
  3916. xhr.addEventListener("load", function () {
  3917. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3918. // Blob as response (XHR2)
  3919. //fileData = xhr.responseText;
  3920. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3921. if (!_this.hasReachedQuota) {
  3922. // Open a transaction to the database
  3923. var transaction = _this.db.transaction([targetStore], "readwrite");
  3924. // the transaction could abort because of a QuotaExceededError error
  3925. transaction.onabort = function (event) {
  3926. try {
  3927. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3928. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3929. this.hasReachedQuota = true;
  3930. }
  3931. }
  3932. catch (ex) { }
  3933. callback(fileData);
  3934. };
  3935. transaction.oncomplete = function (event) {
  3936. callback(fileData);
  3937. };
  3938. var newFile;
  3939. if (targetStore === "scenes") {
  3940. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3941. }
  3942. else {
  3943. newFile = { textureUrl: url, data: fileData };
  3944. }
  3945. try {
  3946. // Put the scene into the database
  3947. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3948. addRequest.onsuccess = function (event) {
  3949. };
  3950. addRequest.onerror = function (event) {
  3951. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3952. };
  3953. }
  3954. catch (ex) {
  3955. callback(fileData);
  3956. }
  3957. }
  3958. else {
  3959. callback(fileData);
  3960. }
  3961. }
  3962. else {
  3963. callback();
  3964. }
  3965. }, false);
  3966. xhr.addEventListener("error", function (event) {
  3967. BABYLON.Tools.Error("error on XHR request.");
  3968. callback();
  3969. }, false);
  3970. xhr.send();
  3971. }
  3972. else {
  3973. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3974. callback();
  3975. }
  3976. };
  3977. Database.IsUASupportingBlobStorage = true;
  3978. Database.IDBStorageEnabled = true;
  3979. Database.parseURL = function (url) {
  3980. var a = document.createElement('a');
  3981. a.href = url;
  3982. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3983. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3984. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3985. return absLocation;
  3986. };
  3987. Database.ReturnFullUrlLocation = function (url) {
  3988. if (url.indexOf("http:/") === -1) {
  3989. return (Database.parseURL(window.location.href) + url);
  3990. }
  3991. else {
  3992. return url;
  3993. }
  3994. };
  3995. return Database;
  3996. }());
  3997. BABYLON.Database = Database;
  3998. })(BABYLON || (BABYLON = {}));
  3999. var BABYLON;
  4000. (function (BABYLON) {
  4001. var Internals;
  4002. (function (Internals) {
  4003. /*
  4004. * Based on jsTGALoader - Javascript loader for TGA file
  4005. * By Vincent Thibault
  4006. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4007. */
  4008. var TGATools = (function () {
  4009. function TGATools() {
  4010. }
  4011. TGATools.GetTGAHeader = function (data) {
  4012. var offset = 0;
  4013. var header = {
  4014. id_length: data[offset++],
  4015. colormap_type: data[offset++],
  4016. image_type: data[offset++],
  4017. colormap_index: data[offset++] | data[offset++] << 8,
  4018. colormap_length: data[offset++] | data[offset++] << 8,
  4019. colormap_size: data[offset++],
  4020. origin: [
  4021. data[offset++] | data[offset++] << 8,
  4022. data[offset++] | data[offset++] << 8
  4023. ],
  4024. width: data[offset++] | data[offset++] << 8,
  4025. height: data[offset++] | data[offset++] << 8,
  4026. pixel_size: data[offset++],
  4027. flags: data[offset++]
  4028. };
  4029. return header;
  4030. };
  4031. TGATools.UploadContent = function (gl, data) {
  4032. // Not enough data to contain header ?
  4033. if (data.length < 19) {
  4034. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4035. return;
  4036. }
  4037. // Read Header
  4038. var offset = 18;
  4039. var header = TGATools.GetTGAHeader(data);
  4040. // Assume it's a valid Targa file.
  4041. if (header.id_length + offset > data.length) {
  4042. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4043. return;
  4044. }
  4045. // Skip not needed data
  4046. offset += header.id_length;
  4047. var use_rle = false;
  4048. var use_pal = false;
  4049. var use_rgb = false;
  4050. var use_grey = false;
  4051. // Get some informations.
  4052. switch (header.image_type) {
  4053. case TGATools._TYPE_RLE_INDEXED:
  4054. use_rle = true;
  4055. case TGATools._TYPE_INDEXED:
  4056. use_pal = true;
  4057. break;
  4058. case TGATools._TYPE_RLE_RGB:
  4059. use_rle = true;
  4060. case TGATools._TYPE_RGB:
  4061. use_rgb = true;
  4062. break;
  4063. case TGATools._TYPE_RLE_GREY:
  4064. use_rle = true;
  4065. case TGATools._TYPE_GREY:
  4066. use_grey = true;
  4067. break;
  4068. }
  4069. var pixel_data;
  4070. var numAlphaBits = header.flags & 0xf;
  4071. var pixel_size = header.pixel_size >> 3;
  4072. var pixel_total = header.width * header.height * pixel_size;
  4073. // Read palettes
  4074. var palettes;
  4075. if (use_pal) {
  4076. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4077. }
  4078. // Read LRE
  4079. if (use_rle) {
  4080. pixel_data = new Uint8Array(pixel_total);
  4081. var c, count, i;
  4082. var localOffset = 0;
  4083. var pixels = new Uint8Array(pixel_size);
  4084. while (offset < pixel_total && localOffset < pixel_total) {
  4085. c = data[offset++];
  4086. count = (c & 0x7f) + 1;
  4087. // RLE pixels
  4088. if (c & 0x80) {
  4089. // Bind pixel tmp array
  4090. for (i = 0; i < pixel_size; ++i) {
  4091. pixels[i] = data[offset++];
  4092. }
  4093. // Copy pixel array
  4094. for (i = 0; i < count; ++i) {
  4095. pixel_data.set(pixels, localOffset + i * pixel_size);
  4096. }
  4097. localOffset += pixel_size * count;
  4098. }
  4099. else {
  4100. count *= pixel_size;
  4101. for (i = 0; i < count; ++i) {
  4102. pixel_data[localOffset + i] = data[offset++];
  4103. }
  4104. localOffset += count;
  4105. }
  4106. }
  4107. }
  4108. else {
  4109. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4110. }
  4111. // Load to texture
  4112. var x_start, y_start, x_step, y_step, y_end, x_end;
  4113. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4114. default:
  4115. case TGATools._ORIGIN_UL:
  4116. x_start = 0;
  4117. x_step = 1;
  4118. x_end = header.width;
  4119. y_start = 0;
  4120. y_step = 1;
  4121. y_end = header.height;
  4122. break;
  4123. case TGATools._ORIGIN_BL:
  4124. x_start = 0;
  4125. x_step = 1;
  4126. x_end = header.width;
  4127. y_start = header.height - 1;
  4128. y_step = -1;
  4129. y_end = -1;
  4130. break;
  4131. case TGATools._ORIGIN_UR:
  4132. x_start = header.width - 1;
  4133. x_step = -1;
  4134. x_end = -1;
  4135. y_start = 0;
  4136. y_step = 1;
  4137. y_end = header.height;
  4138. break;
  4139. case TGATools._ORIGIN_BR:
  4140. x_start = header.width - 1;
  4141. x_step = -1;
  4142. x_end = -1;
  4143. y_start = header.height - 1;
  4144. y_step = -1;
  4145. y_end = -1;
  4146. break;
  4147. }
  4148. // Load the specify method
  4149. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4150. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4151. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4152. };
  4153. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4154. var image = pixel_data, colormap = palettes;
  4155. var width = header.width, height = header.height;
  4156. var color, i = 0, x, y;
  4157. var imageData = new Uint8Array(width * height * 4);
  4158. for (y = y_start; y !== y_end; y += y_step) {
  4159. for (x = x_start; x !== x_end; x += x_step, i++) {
  4160. color = image[i];
  4161. imageData[(x + width * y) * 4 + 3] = 255;
  4162. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4163. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4164. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4165. }
  4166. }
  4167. return imageData;
  4168. };
  4169. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4170. var image = pixel_data;
  4171. var width = header.width, height = header.height;
  4172. var color, i = 0, x, y;
  4173. var imageData = new Uint8Array(width * height * 4);
  4174. for (y = y_start; y !== y_end; y += y_step) {
  4175. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4176. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4177. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4178. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4179. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4180. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4181. }
  4182. }
  4183. return imageData;
  4184. };
  4185. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4186. var image = pixel_data;
  4187. var width = header.width, height = header.height;
  4188. var i = 0, x, y;
  4189. var imageData = new Uint8Array(width * height * 4);
  4190. for (y = y_start; y !== y_end; y += y_step) {
  4191. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4192. imageData[(x + width * y) * 4 + 3] = 255;
  4193. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4194. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4195. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4196. }
  4197. }
  4198. return imageData;
  4199. };
  4200. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4201. var image = pixel_data;
  4202. var width = header.width, height = header.height;
  4203. var i = 0, x, y;
  4204. var imageData = new Uint8Array(width * height * 4);
  4205. for (y = y_start; y !== y_end; y += y_step) {
  4206. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4207. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4208. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4209. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4210. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4211. }
  4212. }
  4213. return imageData;
  4214. };
  4215. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4216. var image = pixel_data;
  4217. var width = header.width, height = header.height;
  4218. var color, i = 0, x, y;
  4219. var imageData = new Uint8Array(width * height * 4);
  4220. for (y = y_start; y !== y_end; y += y_step) {
  4221. for (x = x_start; x !== x_end; x += x_step, i++) {
  4222. color = image[i];
  4223. imageData[(x + width * y) * 4 + 0] = color;
  4224. imageData[(x + width * y) * 4 + 1] = color;
  4225. imageData[(x + width * y) * 4 + 2] = color;
  4226. imageData[(x + width * y) * 4 + 3] = 255;
  4227. }
  4228. }
  4229. return imageData;
  4230. };
  4231. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4232. var image = pixel_data;
  4233. var width = header.width, height = header.height;
  4234. var i = 0, x, y;
  4235. var imageData = new Uint8Array(width * height * 4);
  4236. for (y = y_start; y !== y_end; y += y_step) {
  4237. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4238. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4239. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4240. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4241. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4242. }
  4243. }
  4244. return imageData;
  4245. };
  4246. TGATools._TYPE_NO_DATA = 0;
  4247. TGATools._TYPE_INDEXED = 1;
  4248. TGATools._TYPE_RGB = 2;
  4249. TGATools._TYPE_GREY = 3;
  4250. TGATools._TYPE_RLE_INDEXED = 9;
  4251. TGATools._TYPE_RLE_RGB = 10;
  4252. TGATools._TYPE_RLE_GREY = 11;
  4253. TGATools._ORIGIN_MASK = 0x30;
  4254. TGATools._ORIGIN_SHIFT = 0x04;
  4255. TGATools._ORIGIN_BL = 0x00;
  4256. TGATools._ORIGIN_BR = 0x01;
  4257. TGATools._ORIGIN_UL = 0x02;
  4258. TGATools._ORIGIN_UR = 0x03;
  4259. return TGATools;
  4260. }());
  4261. Internals.TGATools = TGATools;
  4262. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4263. })(BABYLON || (BABYLON = {}));
  4264. var BABYLON;
  4265. (function (BABYLON) {
  4266. var SmartArray = (function () {
  4267. function SmartArray(capacity) {
  4268. this.length = 0;
  4269. this._duplicateId = 0;
  4270. this.data = new Array(capacity);
  4271. this._id = SmartArray._GlobalId++;
  4272. }
  4273. SmartArray.prototype.push = function (value) {
  4274. this.data[this.length++] = value;
  4275. if (this.length > this.data.length) {
  4276. this.data.length *= 2;
  4277. }
  4278. if (!value.__smartArrayFlags) {
  4279. value.__smartArrayFlags = {};
  4280. }
  4281. value.__smartArrayFlags[this._id] = this._duplicateId;
  4282. };
  4283. SmartArray.prototype.pushNoDuplicate = function (value) {
  4284. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4285. return false;
  4286. }
  4287. this.push(value);
  4288. return true;
  4289. };
  4290. SmartArray.prototype.sort = function (compareFn) {
  4291. this.data.sort(compareFn);
  4292. };
  4293. SmartArray.prototype.reset = function () {
  4294. this.length = 0;
  4295. this._duplicateId++;
  4296. };
  4297. SmartArray.prototype.concat = function (array) {
  4298. if (array.length === 0) {
  4299. return;
  4300. }
  4301. if (this.length + array.length > this.data.length) {
  4302. this.data.length = (this.length + array.length) * 2;
  4303. }
  4304. for (var index = 0; index < array.length; index++) {
  4305. this.data[this.length++] = (array.data || array)[index];
  4306. }
  4307. };
  4308. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4309. if (array.length === 0) {
  4310. return;
  4311. }
  4312. if (this.length + array.length > this.data.length) {
  4313. this.data.length = (this.length + array.length) * 2;
  4314. }
  4315. for (var index = 0; index < array.length; index++) {
  4316. var item = (array.data || array)[index];
  4317. this.pushNoDuplicate(item);
  4318. }
  4319. };
  4320. SmartArray.prototype.indexOf = function (value) {
  4321. var position = this.data.indexOf(value);
  4322. if (position >= this.length) {
  4323. return -1;
  4324. }
  4325. return position;
  4326. };
  4327. // Statics
  4328. SmartArray._GlobalId = 0;
  4329. return SmartArray;
  4330. }());
  4331. BABYLON.SmartArray = SmartArray;
  4332. })(BABYLON || (BABYLON = {}));
  4333. var BABYLON;
  4334. (function (BABYLON) {
  4335. /**
  4336. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4337. * The underlying implementation relies on an associative array to ensure the best performances.
  4338. * The value can be anything including 'null' but except 'undefined'
  4339. */
  4340. var StringDictionary = (function () {
  4341. function StringDictionary() {
  4342. this._count = 0;
  4343. this._data = {};
  4344. }
  4345. /**
  4346. * Get a value based from its key
  4347. * @param key the given key to get the matching value from
  4348. * @return the value if found, otherwise undefined is returned
  4349. */
  4350. StringDictionary.prototype.get = function (key) {
  4351. var val = this._data[key];
  4352. if (val !== undefined) {
  4353. return val;
  4354. }
  4355. return undefined;
  4356. };
  4357. /**
  4358. * Get a value from its key or add it if it doesn't exist.
  4359. * This method will ensure you that a given key/data will be present in the dictionary.
  4360. * @param key the given key to get the matching value from
  4361. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4362. * The factory will only be invoked if there's no data for the given key.
  4363. * @return the value corresponding to the key.
  4364. */
  4365. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4366. var val = this.get(key);
  4367. if (val !== undefined) {
  4368. return val;
  4369. }
  4370. val = factory(key);
  4371. if (val) {
  4372. this.add(key, val);
  4373. }
  4374. return val;
  4375. };
  4376. /**
  4377. * Get a value from its key if present in the dictionary otherwise add it
  4378. * @param key the key to get the value from
  4379. * @param val if there's no such key/value pair in the dictionary add it with this value
  4380. * @return the value corresponding to the key
  4381. */
  4382. StringDictionary.prototype.getOrAdd = function (key, val) {
  4383. var curVal = this.get(key);
  4384. if (curVal !== undefined) {
  4385. return curVal;
  4386. }
  4387. this.add(key, val);
  4388. return val;
  4389. };
  4390. /**
  4391. * Check if there's a given key in the dictionary
  4392. * @param key the key to check for
  4393. * @return true if the key is present, false otherwise
  4394. */
  4395. StringDictionary.prototype.contains = function (key) {
  4396. return this._data[key] !== undefined;
  4397. };
  4398. /**
  4399. * Add a new key and its corresponding value
  4400. * @param key the key to add
  4401. * @param value the value corresponding to the key
  4402. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  4403. */
  4404. StringDictionary.prototype.add = function (key, value) {
  4405. if (this._data[key] !== undefined) {
  4406. return false;
  4407. }
  4408. this._data[key] = value;
  4409. ++this._count;
  4410. return true;
  4411. };
  4412. StringDictionary.prototype.set = function (key, value) {
  4413. if (this._data[key] === undefined) {
  4414. return false;
  4415. }
  4416. this._data[key] = value;
  4417. return true;
  4418. };
  4419. /**
  4420. * Remove a key/value from the dictionary.
  4421. * @param key the key to remove
  4422. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4423. */
  4424. StringDictionary.prototype.remove = function (key) {
  4425. if (this.contains(key)) {
  4426. delete this._data[key];
  4427. --this._count;
  4428. return true;
  4429. }
  4430. return false;
  4431. };
  4432. /**
  4433. * Clear the whole content of the dictionary
  4434. */
  4435. StringDictionary.prototype.clear = function () {
  4436. this._data = {};
  4437. this._count = 0;
  4438. };
  4439. Object.defineProperty(StringDictionary.prototype, "count", {
  4440. get: function () {
  4441. return this._count;
  4442. },
  4443. enumerable: true,
  4444. configurable: true
  4445. });
  4446. /**
  4447. * Execute a callback on each key/val of the dictionary.
  4448. * Note that you can remove any element in this dictionary in the callback implementation
  4449. * @param callback the callback to execute on a given key/value pair
  4450. */
  4451. StringDictionary.prototype.forEach = function (callback) {
  4452. for (var cur in this._data) {
  4453. var val = this._data[cur];
  4454. callback(cur, val);
  4455. }
  4456. };
  4457. /**
  4458. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4459. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4460. * Note that you can remove any element in this dictionary in the callback implementation
  4461. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4462. */
  4463. StringDictionary.prototype.first = function (callback) {
  4464. for (var cur in this._data) {
  4465. var val = this._data[cur];
  4466. var res = callback(cur, val);
  4467. if (res) {
  4468. return res;
  4469. }
  4470. }
  4471. return null;
  4472. };
  4473. return StringDictionary;
  4474. }());
  4475. BABYLON.StringDictionary = StringDictionary;
  4476. })(BABYLON || (BABYLON = {}));
  4477. var BABYLON;
  4478. (function (BABYLON) {
  4479. // Screenshots
  4480. var screenshotCanvas;
  4481. var cloneValue = function (source, destinationObject) {
  4482. if (!source)
  4483. return null;
  4484. if (source instanceof BABYLON.Mesh) {
  4485. return null;
  4486. }
  4487. if (source instanceof BABYLON.SubMesh) {
  4488. return source.clone(destinationObject);
  4489. }
  4490. else if (source.clone) {
  4491. return source.clone();
  4492. }
  4493. return null;
  4494. };
  4495. var Tools = (function () {
  4496. function Tools() {
  4497. }
  4498. Tools.Instantiate = function (className) {
  4499. var arr = className.split(".");
  4500. var fn = (window || this);
  4501. for (var i = 0, len = arr.length; i < len; i++) {
  4502. fn = fn[arr[i]];
  4503. }
  4504. if (typeof fn !== "function") {
  4505. return null;
  4506. }
  4507. return fn;
  4508. };
  4509. Tools.SetImmediate = function (action) {
  4510. if (window.setImmediate) {
  4511. window.setImmediate(action);
  4512. }
  4513. else {
  4514. setTimeout(action, 1);
  4515. }
  4516. };
  4517. Tools.IsExponentOfTwo = function (value) {
  4518. var count = 1;
  4519. do {
  4520. count *= 2;
  4521. } while (count < value);
  4522. return count === value;
  4523. };
  4524. Tools.GetExponentOfTwo = function (value, max) {
  4525. var count = 1;
  4526. do {
  4527. count *= 2;
  4528. } while (count < value);
  4529. if (count > max)
  4530. count = max;
  4531. return count;
  4532. };
  4533. Tools.GetFilename = function (path) {
  4534. var index = path.lastIndexOf("/");
  4535. if (index < 0)
  4536. return path;
  4537. return path.substring(index + 1);
  4538. };
  4539. Tools.GetDOMTextContent = function (element) {
  4540. var result = "";
  4541. var child = element.firstChild;
  4542. while (child) {
  4543. if (child.nodeType === 3) {
  4544. result += child.textContent;
  4545. }
  4546. child = child.nextSibling;
  4547. }
  4548. return result;
  4549. };
  4550. Tools.ToDegrees = function (angle) {
  4551. return angle * 180 / Math.PI;
  4552. };
  4553. Tools.ToRadians = function (angle) {
  4554. return angle * Math.PI / 180;
  4555. };
  4556. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4557. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4558. var output = "";
  4559. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4560. var i = 0;
  4561. var bytes = new Uint8Array(buffer);
  4562. while (i < bytes.length) {
  4563. chr1 = bytes[i++];
  4564. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4565. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4566. enc1 = chr1 >> 2;
  4567. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4568. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4569. enc4 = chr3 & 63;
  4570. if (isNaN(chr2)) {
  4571. enc3 = enc4 = 64;
  4572. }
  4573. else if (isNaN(chr3)) {
  4574. enc4 = 64;
  4575. }
  4576. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4577. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4578. }
  4579. return "data:image/png;base64," + output;
  4580. };
  4581. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4582. if (bias === void 0) { bias = null; }
  4583. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4584. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4585. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4586. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4587. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4588. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4589. }
  4590. if (bias) {
  4591. minimum.x -= minimum.x * bias.x + bias.y;
  4592. minimum.y -= minimum.y * bias.x + bias.y;
  4593. minimum.z -= minimum.z * bias.x + bias.y;
  4594. maximum.x += maximum.x * bias.x + bias.y;
  4595. maximum.y += maximum.y * bias.x + bias.y;
  4596. maximum.z += maximum.z * bias.x + bias.y;
  4597. }
  4598. return {
  4599. minimum: minimum,
  4600. maximum: maximum
  4601. };
  4602. };
  4603. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4604. if (bias === void 0) { bias = null; }
  4605. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4606. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4607. if (!stride) {
  4608. stride = 3;
  4609. }
  4610. for (var index = start; index < start + count; index++) {
  4611. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4612. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4613. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4614. }
  4615. if (bias) {
  4616. minimum.x -= minimum.x * bias.x + bias.y;
  4617. minimum.y -= minimum.y * bias.x + bias.y;
  4618. minimum.z -= minimum.z * bias.x + bias.y;
  4619. maximum.x += maximum.x * bias.x + bias.y;
  4620. maximum.y += maximum.y * bias.x + bias.y;
  4621. maximum.z += maximum.z * bias.x + bias.y;
  4622. }
  4623. return {
  4624. minimum: minimum,
  4625. maximum: maximum
  4626. };
  4627. };
  4628. Tools.Vector2ArrayFeeder = function (array) {
  4629. return function (index) {
  4630. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4631. var length = isFloatArray ? array.length / 2 : array.length;
  4632. if (index >= length) {
  4633. return null;
  4634. }
  4635. if (isFloatArray) {
  4636. var fa = array;
  4637. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4638. }
  4639. var a = array;
  4640. return a[index];
  4641. };
  4642. };
  4643. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4644. if (bias === void 0) { bias = null; }
  4645. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4646. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4647. var i = 0;
  4648. var cur = feeder(i++);
  4649. while (cur) {
  4650. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4651. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4652. cur = feeder(i++);
  4653. }
  4654. if (bias) {
  4655. minimum.x -= minimum.x * bias.x + bias.y;
  4656. minimum.y -= minimum.y * bias.x + bias.y;
  4657. maximum.x += maximum.x * bias.x + bias.y;
  4658. maximum.y += maximum.y * bias.x + bias.y;
  4659. }
  4660. return {
  4661. minimum: minimum,
  4662. maximum: maximum
  4663. };
  4664. };
  4665. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4666. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4667. return undefined;
  4668. return Array.isArray(obj) ? obj : [obj];
  4669. };
  4670. // Misc.
  4671. Tools.GetPointerPrefix = function () {
  4672. var eventPrefix = "pointer";
  4673. // Check if pointer events are supported
  4674. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4675. eventPrefix = "mouse";
  4676. }
  4677. return eventPrefix;
  4678. };
  4679. /**
  4680. * @param func - the function to be called
  4681. * @param requester - the object that will request the next frame. Falls back to window.
  4682. */
  4683. Tools.QueueNewFrame = function (func, requester) {
  4684. if (requester === void 0) { requester = window; }
  4685. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4686. /*if(requester.isPresenting) {
  4687. return;
  4688. } else*/ if (requester.requestAnimationFrame)
  4689. requester.requestAnimationFrame(func);
  4690. else if (requester.msRequestAnimationFrame)
  4691. requester.msRequestAnimationFrame(func);
  4692. else if (requester.webkitRequestAnimationFrame)
  4693. requester.webkitRequestAnimationFrame(func);
  4694. else if (requester.mozRequestAnimationFrame)
  4695. requester.mozRequestAnimationFrame(func);
  4696. else if (requester.oRequestAnimationFrame)
  4697. requester.oRequestAnimationFrame(func);
  4698. else {
  4699. window.setTimeout(func, 16);
  4700. }
  4701. };
  4702. Tools.RequestFullscreen = function (element) {
  4703. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4704. if (!requestFunction)
  4705. return;
  4706. requestFunction.call(element);
  4707. };
  4708. Tools.ExitFullscreen = function () {
  4709. if (document.exitFullscreen) {
  4710. document.exitFullscreen();
  4711. }
  4712. else if (document.mozCancelFullScreen) {
  4713. document.mozCancelFullScreen();
  4714. }
  4715. else if (document.webkitCancelFullScreen) {
  4716. document.webkitCancelFullScreen();
  4717. }
  4718. else if (document.msCancelFullScreen) {
  4719. document.msCancelFullScreen();
  4720. }
  4721. };
  4722. Tools.SetCorsBehavior = function (url, img) {
  4723. if (Tools.CorsBehavior) {
  4724. switch (typeof (Tools.CorsBehavior)) {
  4725. case "function":
  4726. var result = Tools.CorsBehavior(url);
  4727. if (result) {
  4728. return result;
  4729. }
  4730. break;
  4731. case "string":
  4732. default:
  4733. img.crossOrigin = Tools.CorsBehavior;
  4734. break;
  4735. }
  4736. }
  4737. };
  4738. // External files
  4739. Tools.CleanUrl = function (url) {
  4740. url = url.replace(/#/mg, "%23");
  4741. return url;
  4742. };
  4743. Tools.LoadImage = function (url, onload, onerror, database) {
  4744. if (url instanceof ArrayBuffer) {
  4745. url = Tools.EncodeArrayBufferTobase64(url);
  4746. }
  4747. url = Tools.CleanUrl(url);
  4748. var img = new Image();
  4749. if (url.substr(0, 5) !== "data:") {
  4750. Tools.SetCorsBehavior(url, img);
  4751. }
  4752. img.onload = function () {
  4753. onload(img);
  4754. };
  4755. img.onerror = function (err) {
  4756. Tools.Error("Error while trying to load texture: " + url);
  4757. if (Tools.UseFallbackTexture) {
  4758. 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";
  4759. onload(img);
  4760. }
  4761. else {
  4762. onerror();
  4763. }
  4764. };
  4765. var noIndexedDB = function () {
  4766. img.src = url;
  4767. };
  4768. var loadFromIndexedDB = function () {
  4769. database.loadImageFromDB(url, img);
  4770. };
  4771. //ANY database to do!
  4772. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4773. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4774. }
  4775. else {
  4776. if (url.indexOf("file:") === -1) {
  4777. noIndexedDB();
  4778. }
  4779. else {
  4780. try {
  4781. var textureName = url.substring(5).toLowerCase();
  4782. var blobURL;
  4783. try {
  4784. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4785. }
  4786. catch (ex) {
  4787. // Chrome doesn't support oneTimeOnly parameter
  4788. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4789. }
  4790. img.src = blobURL;
  4791. }
  4792. catch (e) {
  4793. img.src = null;
  4794. }
  4795. }
  4796. }
  4797. return img;
  4798. };
  4799. //ANY
  4800. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4801. url = Tools.CleanUrl(url);
  4802. var noIndexedDB = function () {
  4803. var request = new XMLHttpRequest();
  4804. var loadUrl = Tools.BaseUrl + url;
  4805. request.open('GET', loadUrl, true);
  4806. if (useArrayBuffer) {
  4807. request.responseType = "arraybuffer";
  4808. }
  4809. request.onprogress = progressCallBack;
  4810. request.onreadystatechange = function () {
  4811. if (request.readyState === 4) {
  4812. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4813. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4814. callback(!useArrayBuffer ? request.responseText : request.response);
  4815. }
  4816. else {
  4817. if (onError) {
  4818. onError();
  4819. }
  4820. else {
  4821. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4822. }
  4823. }
  4824. }
  4825. };
  4826. request.send(null);
  4827. };
  4828. var loadFromIndexedDB = function () {
  4829. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4830. };
  4831. if (url.indexOf("file:") !== -1) {
  4832. var fileName = url.substring(5).toLowerCase();
  4833. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4834. }
  4835. else {
  4836. // Caching all files
  4837. if (database && database.enableSceneOffline) {
  4838. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4839. }
  4840. else {
  4841. noIndexedDB();
  4842. }
  4843. }
  4844. };
  4845. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4846. var reader = new FileReader();
  4847. reader.onload = function (e) {
  4848. //target doesn't have result from ts 1.3
  4849. callback(e.target['result']);
  4850. };
  4851. reader.onprogress = progressCallback;
  4852. reader.readAsDataURL(fileToLoad);
  4853. };
  4854. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4855. var reader = new FileReader();
  4856. reader.onerror = function (e) {
  4857. Tools.Log("Error while reading file: " + fileToLoad.name);
  4858. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4859. };
  4860. reader.onload = function (e) {
  4861. //target doesn't have result from ts 1.3
  4862. callback(e.target['result']);
  4863. };
  4864. reader.onprogress = progressCallBack;
  4865. if (!useArrayBuffer) {
  4866. // Asynchronous read
  4867. reader.readAsText(fileToLoad);
  4868. }
  4869. else {
  4870. reader.readAsArrayBuffer(fileToLoad);
  4871. }
  4872. };
  4873. //returns a downloadable url to a file content.
  4874. Tools.FileAsURL = function (content) {
  4875. var fileBlob = new Blob([content]);
  4876. var url = window.URL || window.webkitURL;
  4877. var link = url.createObjectURL(fileBlob);
  4878. return link;
  4879. };
  4880. // Misc.
  4881. Tools.Format = function (value, decimals) {
  4882. if (decimals === void 0) { decimals = 2; }
  4883. return value.toFixed(decimals);
  4884. };
  4885. Tools.CheckExtends = function (v, min, max) {
  4886. if (v.x < min.x)
  4887. min.x = v.x;
  4888. if (v.y < min.y)
  4889. min.y = v.y;
  4890. if (v.z < min.z)
  4891. min.z = v.z;
  4892. if (v.x > max.x)
  4893. max.x = v.x;
  4894. if (v.y > max.y)
  4895. max.y = v.y;
  4896. if (v.z > max.z)
  4897. max.z = v.z;
  4898. };
  4899. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4900. for (var prop in source) {
  4901. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4902. continue;
  4903. }
  4904. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4905. continue;
  4906. }
  4907. var sourceValue = source[prop];
  4908. var typeOfSourceValue = typeof sourceValue;
  4909. if (typeOfSourceValue === "function") {
  4910. continue;
  4911. }
  4912. if (typeOfSourceValue === "object") {
  4913. if (sourceValue instanceof Array) {
  4914. destination[prop] = [];
  4915. if (sourceValue.length > 0) {
  4916. if (typeof sourceValue[0] == "object") {
  4917. for (var index = 0; index < sourceValue.length; index++) {
  4918. var clonedValue = cloneValue(sourceValue[index], destination);
  4919. if (destination[prop].indexOf(clonedValue) === -1) {
  4920. destination[prop].push(clonedValue);
  4921. }
  4922. }
  4923. }
  4924. else {
  4925. destination[prop] = sourceValue.slice(0);
  4926. }
  4927. }
  4928. }
  4929. else {
  4930. destination[prop] = cloneValue(sourceValue, destination);
  4931. }
  4932. }
  4933. else {
  4934. destination[prop] = sourceValue;
  4935. }
  4936. }
  4937. };
  4938. Tools.IsEmpty = function (obj) {
  4939. for (var i in obj) {
  4940. return false;
  4941. }
  4942. return true;
  4943. };
  4944. Tools.RegisterTopRootEvents = function (events) {
  4945. for (var index = 0; index < events.length; index++) {
  4946. var event = events[index];
  4947. window.addEventListener(event.name, event.handler, false);
  4948. try {
  4949. if (window.parent) {
  4950. window.parent.addEventListener(event.name, event.handler, false);
  4951. }
  4952. }
  4953. catch (e) {
  4954. }
  4955. }
  4956. };
  4957. Tools.UnregisterTopRootEvents = function (events) {
  4958. for (var index = 0; index < events.length; index++) {
  4959. var event = events[index];
  4960. window.removeEventListener(event.name, event.handler);
  4961. try {
  4962. if (window.parent) {
  4963. window.parent.removeEventListener(event.name, event.handler);
  4964. }
  4965. }
  4966. catch (e) {
  4967. }
  4968. }
  4969. };
  4970. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  4971. if (mimeType === void 0) { mimeType = "image/png"; }
  4972. // Read the contents of the framebuffer
  4973. var numberOfChannelsByLine = width * 4;
  4974. var halfHeight = height / 2;
  4975. //Reading datas from WebGL
  4976. var data = engine.readPixels(0, 0, width, height);
  4977. //To flip image on Y axis.
  4978. for (var i = 0; i < halfHeight; i++) {
  4979. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4980. var currentCell = j + i * numberOfChannelsByLine;
  4981. var targetLine = height - i - 1;
  4982. var targetCell = j + targetLine * numberOfChannelsByLine;
  4983. var temp = data[currentCell];
  4984. data[currentCell] = data[targetCell];
  4985. data[targetCell] = temp;
  4986. }
  4987. }
  4988. // Create a 2D canvas to store the result
  4989. if (!screenshotCanvas) {
  4990. screenshotCanvas = document.createElement('canvas');
  4991. }
  4992. screenshotCanvas.width = width;
  4993. screenshotCanvas.height = height;
  4994. var context = screenshotCanvas.getContext('2d');
  4995. // Copy the pixels to a 2D canvas
  4996. var imageData = context.createImageData(width, height);
  4997. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4998. var castData = imageData.data;
  4999. castData.set(data);
  5000. context.putImageData(imageData, 0, 0);
  5001. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5002. if (successCallback) {
  5003. successCallback(base64Image);
  5004. }
  5005. else {
  5006. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5007. if (("download" in document.createElement("a"))) {
  5008. var a = window.document.createElement("a");
  5009. a.href = base64Image;
  5010. var date = new Date();
  5011. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5012. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5013. window.document.body.appendChild(a);
  5014. a.addEventListener("click", function () {
  5015. a.parentElement.removeChild(a);
  5016. });
  5017. a.click();
  5018. }
  5019. else {
  5020. var newWindow = window.open("");
  5021. var img = newWindow.document.createElement("img");
  5022. img.src = base64Image;
  5023. newWindow.document.body.appendChild(img);
  5024. }
  5025. }
  5026. };
  5027. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5028. if (mimeType === void 0) { mimeType = "image/png"; }
  5029. var width;
  5030. var height;
  5031. //If a precision value is specified
  5032. if (size.precision) {
  5033. width = Math.round(engine.getRenderWidth() * size.precision);
  5034. height = Math.round(width / engine.getAspectRatio(camera));
  5035. size = { width: width, height: height };
  5036. }
  5037. else if (size.width && size.height) {
  5038. width = size.width;
  5039. height = size.height;
  5040. }
  5041. else if (size.width && !size.height) {
  5042. width = size.width;
  5043. height = Math.round(width / engine.getAspectRatio(camera));
  5044. size = { width: width, height: height };
  5045. }
  5046. else if (size.height && !size.width) {
  5047. height = size.height;
  5048. width = Math.round(height * engine.getAspectRatio(camera));
  5049. size = { width: width, height: height };
  5050. }
  5051. else if (!isNaN(size)) {
  5052. height = size;
  5053. width = size;
  5054. }
  5055. else {
  5056. Tools.Error("Invalid 'size' parameter !");
  5057. return;
  5058. }
  5059. var scene = camera.getScene();
  5060. var previousCamera = null;
  5061. if (scene.activeCamera !== camera) {
  5062. previousCamera = scene.activeCamera;
  5063. scene.activeCamera = camera;
  5064. }
  5065. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5066. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5067. texture.renderList = scene.meshes;
  5068. texture.onAfterRenderObservable.add(function () {
  5069. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5070. });
  5071. scene.incrementRenderId();
  5072. scene.resetCachedMaterial();
  5073. texture.render(true);
  5074. texture.dispose();
  5075. if (previousCamera) {
  5076. scene.activeCamera = previousCamera;
  5077. }
  5078. camera.getProjectionMatrix(true); // Force cache refresh;
  5079. };
  5080. // XHR response validator for local file scenario
  5081. Tools.ValidateXHRData = function (xhr, dataType) {
  5082. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5083. if (dataType === void 0) { dataType = 7; }
  5084. try {
  5085. if (dataType & 1) {
  5086. if (xhr.responseText && xhr.responseText.length > 0) {
  5087. return true;
  5088. }
  5089. else if (dataType === 1) {
  5090. return false;
  5091. }
  5092. }
  5093. if (dataType & 2) {
  5094. // Check header width and height since there is no "TGA" magic number
  5095. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5096. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5097. return true;
  5098. }
  5099. else if (dataType === 2) {
  5100. return false;
  5101. }
  5102. }
  5103. if (dataType & 4) {
  5104. // Check for the "DDS" magic number
  5105. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5106. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5107. return true;
  5108. }
  5109. else {
  5110. return false;
  5111. }
  5112. }
  5113. }
  5114. catch (e) {
  5115. }
  5116. return false;
  5117. };
  5118. Object.defineProperty(Tools, "NoneLogLevel", {
  5119. get: function () {
  5120. return Tools._NoneLogLevel;
  5121. },
  5122. enumerable: true,
  5123. configurable: true
  5124. });
  5125. Object.defineProperty(Tools, "MessageLogLevel", {
  5126. get: function () {
  5127. return Tools._MessageLogLevel;
  5128. },
  5129. enumerable: true,
  5130. configurable: true
  5131. });
  5132. Object.defineProperty(Tools, "WarningLogLevel", {
  5133. get: function () {
  5134. return Tools._WarningLogLevel;
  5135. },
  5136. enumerable: true,
  5137. configurable: true
  5138. });
  5139. Object.defineProperty(Tools, "ErrorLogLevel", {
  5140. get: function () {
  5141. return Tools._ErrorLogLevel;
  5142. },
  5143. enumerable: true,
  5144. configurable: true
  5145. });
  5146. Object.defineProperty(Tools, "AllLogLevel", {
  5147. get: function () {
  5148. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5149. },
  5150. enumerable: true,
  5151. configurable: true
  5152. });
  5153. Tools._AddLogEntry = function (entry) {
  5154. Tools._LogCache = entry + Tools._LogCache;
  5155. if (Tools.OnNewCacheEntry) {
  5156. Tools.OnNewCacheEntry(entry);
  5157. }
  5158. };
  5159. Tools._FormatMessage = function (message) {
  5160. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5161. var date = new Date();
  5162. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5163. };
  5164. Tools._LogDisabled = function (message) {
  5165. // nothing to do
  5166. };
  5167. Tools._LogEnabled = function (message) {
  5168. var formattedMessage = Tools._FormatMessage(message);
  5169. console.log("BJS - " + formattedMessage);
  5170. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5171. Tools._AddLogEntry(entry);
  5172. };
  5173. Tools._WarnDisabled = function (message) {
  5174. // nothing to do
  5175. };
  5176. Tools._WarnEnabled = function (message) {
  5177. var formattedMessage = Tools._FormatMessage(message);
  5178. console.warn("BJS - " + formattedMessage);
  5179. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5180. Tools._AddLogEntry(entry);
  5181. };
  5182. Tools._ErrorDisabled = function (message) {
  5183. // nothing to do
  5184. };
  5185. Tools._ErrorEnabled = function (message) {
  5186. Tools.errorsCount++;
  5187. var formattedMessage = Tools._FormatMessage(message);
  5188. console.error("BJS - " + formattedMessage);
  5189. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5190. Tools._AddLogEntry(entry);
  5191. };
  5192. Object.defineProperty(Tools, "LogCache", {
  5193. get: function () {
  5194. return Tools._LogCache;
  5195. },
  5196. enumerable: true,
  5197. configurable: true
  5198. });
  5199. Tools.ClearLogCache = function () {
  5200. Tools._LogCache = "";
  5201. Tools.errorsCount = 0;
  5202. };
  5203. Object.defineProperty(Tools, "LogLevels", {
  5204. set: function (level) {
  5205. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5206. Tools.Log = Tools._LogEnabled;
  5207. }
  5208. else {
  5209. Tools.Log = Tools._LogDisabled;
  5210. }
  5211. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5212. Tools.Warn = Tools._WarnEnabled;
  5213. }
  5214. else {
  5215. Tools.Warn = Tools._WarnDisabled;
  5216. }
  5217. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5218. Tools.Error = Tools._ErrorEnabled;
  5219. }
  5220. else {
  5221. Tools.Error = Tools._ErrorDisabled;
  5222. }
  5223. },
  5224. enumerable: true,
  5225. configurable: true
  5226. });
  5227. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5228. get: function () {
  5229. return Tools._PerformanceNoneLogLevel;
  5230. },
  5231. enumerable: true,
  5232. configurable: true
  5233. });
  5234. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5235. get: function () {
  5236. return Tools._PerformanceUserMarkLogLevel;
  5237. },
  5238. enumerable: true,
  5239. configurable: true
  5240. });
  5241. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5242. get: function () {
  5243. return Tools._PerformanceConsoleLogLevel;
  5244. },
  5245. enumerable: true,
  5246. configurable: true
  5247. });
  5248. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5249. set: function (level) {
  5250. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5251. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5252. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5253. return;
  5254. }
  5255. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5256. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5257. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5258. return;
  5259. }
  5260. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5261. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5262. },
  5263. enumerable: true,
  5264. configurable: true
  5265. });
  5266. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5267. };
  5268. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5269. };
  5270. Tools._StartUserMark = function (counterName, condition) {
  5271. if (condition === void 0) { condition = true; }
  5272. if (!condition || !Tools._performance.mark) {
  5273. return;
  5274. }
  5275. Tools._performance.mark(counterName + "-Begin");
  5276. };
  5277. Tools._EndUserMark = function (counterName, condition) {
  5278. if (condition === void 0) { condition = true; }
  5279. if (!condition || !Tools._performance.mark) {
  5280. return;
  5281. }
  5282. Tools._performance.mark(counterName + "-End");
  5283. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5284. };
  5285. Tools._StartPerformanceConsole = function (counterName, condition) {
  5286. if (condition === void 0) { condition = true; }
  5287. if (!condition) {
  5288. return;
  5289. }
  5290. Tools._StartUserMark(counterName, condition);
  5291. if (console.time) {
  5292. console.time(counterName);
  5293. }
  5294. };
  5295. Tools._EndPerformanceConsole = function (counterName, condition) {
  5296. if (condition === void 0) { condition = true; }
  5297. if (!condition) {
  5298. return;
  5299. }
  5300. Tools._EndUserMark(counterName, condition);
  5301. if (console.time) {
  5302. console.timeEnd(counterName);
  5303. }
  5304. };
  5305. Object.defineProperty(Tools, "Now", {
  5306. get: function () {
  5307. if (window.performance && window.performance.now) {
  5308. return window.performance.now();
  5309. }
  5310. return new Date().getTime();
  5311. },
  5312. enumerable: true,
  5313. configurable: true
  5314. });
  5315. /**
  5316. * This method will return the name of the class used to create the instance of the given object.
  5317. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5318. * @param object the object to get the class name from
  5319. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5320. */
  5321. Tools.getClassName = function (object, isType) {
  5322. if (isType === void 0) { isType = false; }
  5323. var name = null;
  5324. if (!isType && object.getClassName) {
  5325. name = object.getClassName();
  5326. }
  5327. else {
  5328. if (object instanceof Object) {
  5329. var classObj = isType ? object : Object.getPrototypeOf(object);
  5330. name = classObj.constructor["__bjsclassName__"];
  5331. }
  5332. if (!name) {
  5333. name = typeof object;
  5334. }
  5335. }
  5336. return name;
  5337. };
  5338. Tools.first = function (array, predicate) {
  5339. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5340. var el = array_1[_i];
  5341. if (predicate(el)) {
  5342. return el;
  5343. }
  5344. }
  5345. };
  5346. /**
  5347. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  5348. * @param array
  5349. */
  5350. Tools.arrayOrStringFeeder = function (array) {
  5351. return function (index) {
  5352. if (index >= array.length) {
  5353. return null;
  5354. }
  5355. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5356. if (val && val.getHashCode) {
  5357. val = val.getHashCode();
  5358. }
  5359. if (typeof val === "string") {
  5360. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5361. }
  5362. return val;
  5363. };
  5364. };
  5365. /**
  5366. * Compute the hashCode of a stream of number
  5367. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5368. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5369. * @return the hash code computed
  5370. */
  5371. Tools.hashCodeFromStream = function (feeder) {
  5372. // Based from here: http://stackoverflow.com/a/7616484/802124
  5373. var hash = 0;
  5374. var index = 0;
  5375. var chr = feeder(index++);
  5376. while (chr != null) {
  5377. hash = ((hash << 5) - hash) + chr;
  5378. hash |= 0; // Convert to 32bit integer
  5379. chr = feeder(index++);
  5380. }
  5381. return hash;
  5382. };
  5383. Tools.BaseUrl = "";
  5384. Tools.CorsBehavior = "anonymous";
  5385. Tools.UseFallbackTexture = true;
  5386. // Logs
  5387. Tools._NoneLogLevel = 0;
  5388. Tools._MessageLogLevel = 1;
  5389. Tools._WarningLogLevel = 2;
  5390. Tools._ErrorLogLevel = 4;
  5391. Tools._LogCache = "";
  5392. Tools.errorsCount = 0;
  5393. Tools.Log = Tools._LogEnabled;
  5394. Tools.Warn = Tools._WarnEnabled;
  5395. Tools.Error = Tools._ErrorEnabled;
  5396. // Performances
  5397. Tools._PerformanceNoneLogLevel = 0;
  5398. Tools._PerformanceUserMarkLogLevel = 1;
  5399. Tools._PerformanceConsoleLogLevel = 2;
  5400. Tools._performance = window.performance;
  5401. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5402. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5403. return Tools;
  5404. }());
  5405. BABYLON.Tools = Tools;
  5406. /**
  5407. * This class is used to track a performance counter which is number based.
  5408. * The user has access to many properties which give statistics of different nature
  5409. *
  5410. * The implementer can track two kinds of Performance Counter: time and count
  5411. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  5412. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  5413. */
  5414. var PerfCounter = (function () {
  5415. function PerfCounter() {
  5416. this._startMonitoringTime = 0;
  5417. this._min = 0;
  5418. this._max = 0;
  5419. this._average = 0;
  5420. this._lastSecAverage = 0;
  5421. this._current = 0;
  5422. this._totalValueCount = 0;
  5423. this._totalAccumulated = 0;
  5424. this._lastSecAccumulated = 0;
  5425. this._lastSecTime = 0;
  5426. this._lastSecValueCount = 0;
  5427. }
  5428. Object.defineProperty(PerfCounter.prototype, "min", {
  5429. /**
  5430. * Returns the smallest value ever
  5431. */
  5432. get: function () {
  5433. return this._min;
  5434. },
  5435. enumerable: true,
  5436. configurable: true
  5437. });
  5438. Object.defineProperty(PerfCounter.prototype, "max", {
  5439. /**
  5440. * Returns the biggest value ever
  5441. */
  5442. get: function () {
  5443. return this._max;
  5444. },
  5445. enumerable: true,
  5446. configurable: true
  5447. });
  5448. Object.defineProperty(PerfCounter.prototype, "average", {
  5449. /**
  5450. * Returns the average value since the performance counter is running
  5451. */
  5452. get: function () {
  5453. return this._average;
  5454. },
  5455. enumerable: true,
  5456. configurable: true
  5457. });
  5458. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5459. /**
  5460. * Returns the average value of the last second the counter was monitored
  5461. */
  5462. get: function () {
  5463. return this._lastSecAverage;
  5464. },
  5465. enumerable: true,
  5466. configurable: true
  5467. });
  5468. Object.defineProperty(PerfCounter.prototype, "current", {
  5469. /**
  5470. * Returns the current value
  5471. */
  5472. get: function () {
  5473. return this._current;
  5474. },
  5475. enumerable: true,
  5476. configurable: true
  5477. });
  5478. Object.defineProperty(PerfCounter.prototype, "total", {
  5479. get: function () {
  5480. return this._totalAccumulated;
  5481. },
  5482. enumerable: true,
  5483. configurable: true
  5484. });
  5485. /**
  5486. * Call this method to start monitoring a new frame.
  5487. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  5488. */
  5489. PerfCounter.prototype.fetchNewFrame = function () {
  5490. this._totalValueCount++;
  5491. this._current = 0;
  5492. this._lastSecValueCount++;
  5493. };
  5494. /**
  5495. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5496. * @param newCount the count value to add to the monitored count
  5497. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  5498. */
  5499. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5500. this._current += newCount;
  5501. if (fetchResult) {
  5502. this._fetchResult();
  5503. }
  5504. };
  5505. /**
  5506. * Start monitoring this performance counter
  5507. */
  5508. PerfCounter.prototype.beginMonitoring = function () {
  5509. this._startMonitoringTime = Tools.Now;
  5510. };
  5511. /**
  5512. * Compute the time lapsed since the previous beginMonitoring() call.
  5513. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  5514. */
  5515. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5516. if (newFrame === void 0) { newFrame = true; }
  5517. if (newFrame) {
  5518. this.fetchNewFrame();
  5519. }
  5520. var currentTime = Tools.Now;
  5521. this._current = currentTime - this._startMonitoringTime;
  5522. if (newFrame) {
  5523. this._fetchResult();
  5524. }
  5525. };
  5526. PerfCounter.prototype._fetchResult = function () {
  5527. this._totalAccumulated += this._current;
  5528. this._lastSecAccumulated += this._current;
  5529. // Min/Max update
  5530. this._min = Math.min(this._min, this._current);
  5531. this._max = Math.max(this._max, this._current);
  5532. this._average = this._totalAccumulated / this._totalValueCount;
  5533. // Reset last sec?
  5534. var now = Tools.Now;
  5535. if ((now - this._lastSecTime) > 1000) {
  5536. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5537. this._lastSecTime = now;
  5538. this._lastSecAccumulated = 0;
  5539. this._lastSecValueCount = 0;
  5540. }
  5541. };
  5542. return PerfCounter;
  5543. }());
  5544. BABYLON.PerfCounter = PerfCounter;
  5545. /**
  5546. * Use this className as a decorator on a given class definition to add it a name.
  5547. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5548. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5549. * @param name
  5550. */
  5551. function className(name) {
  5552. return function (target) {
  5553. target["__bjsclassName__"] = name;
  5554. };
  5555. }
  5556. BABYLON.className = className;
  5557. /**
  5558. * An implementation of a loop for asynchronous functions.
  5559. */
  5560. var AsyncLoop = (function () {
  5561. /**
  5562. * Constroctor.
  5563. * @param iterations the number of iterations.
  5564. * @param _fn the function to run each iteration
  5565. * @param _successCallback the callback that will be called upon succesful execution
  5566. * @param offset starting offset.
  5567. */
  5568. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5569. if (offset === void 0) { offset = 0; }
  5570. this.iterations = iterations;
  5571. this._fn = _fn;
  5572. this._successCallback = _successCallback;
  5573. this.index = offset - 1;
  5574. this._done = false;
  5575. }
  5576. /**
  5577. * Execute the next iteration. Must be called after the last iteration was finished.
  5578. */
  5579. AsyncLoop.prototype.executeNext = function () {
  5580. if (!this._done) {
  5581. if (this.index + 1 < this.iterations) {
  5582. ++this.index;
  5583. this._fn(this);
  5584. }
  5585. else {
  5586. this.breakLoop();
  5587. }
  5588. }
  5589. };
  5590. /**
  5591. * Break the loop and run the success callback.
  5592. */
  5593. AsyncLoop.prototype.breakLoop = function () {
  5594. this._done = true;
  5595. this._successCallback();
  5596. };
  5597. /**
  5598. * Helper function
  5599. */
  5600. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5601. if (offset === void 0) { offset = 0; }
  5602. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5603. loop.executeNext();
  5604. return loop;
  5605. };
  5606. /**
  5607. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5608. * @param iterations total number of iterations
  5609. * @param syncedIterations number of synchronous iterations in each async iteration.
  5610. * @param fn the function to call each iteration.
  5611. * @param callback a success call back that will be called when iterating stops.
  5612. * @param breakFunction a break condition (optional)
  5613. * @param timeout timeout settings for the setTimeout function. default - 0.
  5614. * @constructor
  5615. */
  5616. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5617. if (timeout === void 0) { timeout = 0; }
  5618. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5619. if (breakFunction && breakFunction())
  5620. loop.breakLoop();
  5621. else {
  5622. setTimeout(function () {
  5623. for (var i = 0; i < syncedIterations; ++i) {
  5624. var iteration = (loop.index * syncedIterations) + i;
  5625. if (iteration >= iterations)
  5626. break;
  5627. fn(iteration);
  5628. if (breakFunction && breakFunction()) {
  5629. loop.breakLoop();
  5630. break;
  5631. }
  5632. }
  5633. loop.executeNext();
  5634. }, timeout);
  5635. }
  5636. }, callback);
  5637. };
  5638. return AsyncLoop;
  5639. }());
  5640. BABYLON.AsyncLoop = AsyncLoop;
  5641. })(BABYLON || (BABYLON = {}));
  5642. var BABYLON;
  5643. (function (BABYLON) {
  5644. var Internals;
  5645. (function (Internals) {
  5646. var _AlphaState = (function () {
  5647. function _AlphaState() {
  5648. this._isAlphaBlendDirty = false;
  5649. this._isBlendFunctionParametersDirty = false;
  5650. this._alphaBlend = false;
  5651. this._blendFunctionParameters = new Array(4);
  5652. }
  5653. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5654. get: function () {
  5655. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5656. },
  5657. enumerable: true,
  5658. configurable: true
  5659. });
  5660. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5661. get: function () {
  5662. return this._alphaBlend;
  5663. },
  5664. set: function (value) {
  5665. if (this._alphaBlend === value) {
  5666. return;
  5667. }
  5668. this._alphaBlend = value;
  5669. this._isAlphaBlendDirty = true;
  5670. },
  5671. enumerable: true,
  5672. configurable: true
  5673. });
  5674. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5675. if (this._blendFunctionParameters[0] === value0 &&
  5676. this._blendFunctionParameters[1] === value1 &&
  5677. this._blendFunctionParameters[2] === value2 &&
  5678. this._blendFunctionParameters[3] === value3) {
  5679. return;
  5680. }
  5681. this._blendFunctionParameters[0] = value0;
  5682. this._blendFunctionParameters[1] = value1;
  5683. this._blendFunctionParameters[2] = value2;
  5684. this._blendFunctionParameters[3] = value3;
  5685. this._isBlendFunctionParametersDirty = true;
  5686. };
  5687. _AlphaState.prototype.reset = function () {
  5688. this._alphaBlend = false;
  5689. this._blendFunctionParameters[0] = null;
  5690. this._blendFunctionParameters[1] = null;
  5691. this._blendFunctionParameters[2] = null;
  5692. this._blendFunctionParameters[3] = null;
  5693. this._isAlphaBlendDirty = true;
  5694. this._isBlendFunctionParametersDirty = false;
  5695. };
  5696. _AlphaState.prototype.apply = function (gl) {
  5697. if (!this.isDirty) {
  5698. return;
  5699. }
  5700. // Alpha blend
  5701. if (this._isAlphaBlendDirty) {
  5702. if (this._alphaBlend) {
  5703. gl.enable(gl.BLEND);
  5704. }
  5705. else {
  5706. gl.disable(gl.BLEND);
  5707. }
  5708. this._isAlphaBlendDirty = false;
  5709. }
  5710. // Alpha function
  5711. if (this._isBlendFunctionParametersDirty) {
  5712. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5713. this._isBlendFunctionParametersDirty = false;
  5714. }
  5715. };
  5716. return _AlphaState;
  5717. }());
  5718. Internals._AlphaState = _AlphaState;
  5719. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5720. })(BABYLON || (BABYLON = {}));
  5721. var BABYLON;
  5722. (function (BABYLON) {
  5723. var Internals;
  5724. (function (Internals) {
  5725. var _DepthCullingState = (function () {
  5726. function _DepthCullingState() {
  5727. this._isDepthTestDirty = false;
  5728. this._isDepthMaskDirty = false;
  5729. this._isDepthFuncDirty = false;
  5730. this._isCullFaceDirty = false;
  5731. this._isCullDirty = false;
  5732. this._isZOffsetDirty = false;
  5733. }
  5734. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5735. get: function () {
  5736. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5737. },
  5738. enumerable: true,
  5739. configurable: true
  5740. });
  5741. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5742. get: function () {
  5743. return this._zOffset;
  5744. },
  5745. set: function (value) {
  5746. if (this._zOffset === value) {
  5747. return;
  5748. }
  5749. this._zOffset = value;
  5750. this._isZOffsetDirty = true;
  5751. },
  5752. enumerable: true,
  5753. configurable: true
  5754. });
  5755. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5756. get: function () {
  5757. return this._cullFace;
  5758. },
  5759. set: function (value) {
  5760. if (this._cullFace === value) {
  5761. return;
  5762. }
  5763. this._cullFace = value;
  5764. this._isCullFaceDirty = true;
  5765. },
  5766. enumerable: true,
  5767. configurable: true
  5768. });
  5769. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5770. get: function () {
  5771. return this._cull;
  5772. },
  5773. set: function (value) {
  5774. if (this._cull === value) {
  5775. return;
  5776. }
  5777. this._cull = value;
  5778. this._isCullDirty = true;
  5779. },
  5780. enumerable: true,
  5781. configurable: true
  5782. });
  5783. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5784. get: function () {
  5785. return this._depthFunc;
  5786. },
  5787. set: function (value) {
  5788. if (this._depthFunc === value) {
  5789. return;
  5790. }
  5791. this._depthFunc = value;
  5792. this._isDepthFuncDirty = true;
  5793. },
  5794. enumerable: true,
  5795. configurable: true
  5796. });
  5797. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5798. get: function () {
  5799. return this._depthMask;
  5800. },
  5801. set: function (value) {
  5802. if (this._depthMask === value) {
  5803. return;
  5804. }
  5805. this._depthMask = value;
  5806. this._isDepthMaskDirty = true;
  5807. },
  5808. enumerable: true,
  5809. configurable: true
  5810. });
  5811. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5812. get: function () {
  5813. return this._depthTest;
  5814. },
  5815. set: function (value) {
  5816. if (this._depthTest === value) {
  5817. return;
  5818. }
  5819. this._depthTest = value;
  5820. this._isDepthTestDirty = true;
  5821. },
  5822. enumerable: true,
  5823. configurable: true
  5824. });
  5825. _DepthCullingState.prototype.reset = function () {
  5826. this._depthMask = true;
  5827. this._depthTest = true;
  5828. this._depthFunc = null;
  5829. this._cullFace = null;
  5830. this._cull = null;
  5831. this._zOffset = 0;
  5832. this._isDepthTestDirty = true;
  5833. this._isDepthMaskDirty = true;
  5834. this._isDepthFuncDirty = false;
  5835. this._isCullFaceDirty = false;
  5836. this._isCullDirty = false;
  5837. this._isZOffsetDirty = false;
  5838. };
  5839. _DepthCullingState.prototype.apply = function (gl) {
  5840. if (!this.isDirty) {
  5841. return;
  5842. }
  5843. // Cull
  5844. if (this._isCullDirty) {
  5845. if (this.cull) {
  5846. gl.enable(gl.CULL_FACE);
  5847. }
  5848. else {
  5849. gl.disable(gl.CULL_FACE);
  5850. }
  5851. this._isCullDirty = false;
  5852. }
  5853. // Cull face
  5854. if (this._isCullFaceDirty) {
  5855. gl.cullFace(this.cullFace);
  5856. this._isCullFaceDirty = false;
  5857. }
  5858. // Depth mask
  5859. if (this._isDepthMaskDirty) {
  5860. gl.depthMask(this.depthMask);
  5861. this._isDepthMaskDirty = false;
  5862. }
  5863. // Depth test
  5864. if (this._isDepthTestDirty) {
  5865. if (this.depthTest) {
  5866. gl.enable(gl.DEPTH_TEST);
  5867. }
  5868. else {
  5869. gl.disable(gl.DEPTH_TEST);
  5870. }
  5871. this._isDepthTestDirty = false;
  5872. }
  5873. // Depth func
  5874. if (this._isDepthFuncDirty) {
  5875. gl.depthFunc(this.depthFunc);
  5876. this._isDepthFuncDirty = false;
  5877. }
  5878. // zOffset
  5879. if (this._isZOffsetDirty) {
  5880. if (this.zOffset) {
  5881. gl.enable(gl.POLYGON_OFFSET_FILL);
  5882. gl.polygonOffset(this.zOffset, 0);
  5883. }
  5884. else {
  5885. gl.disable(gl.POLYGON_OFFSET_FILL);
  5886. }
  5887. this._isZOffsetDirty = false;
  5888. }
  5889. };
  5890. return _DepthCullingState;
  5891. }());
  5892. Internals._DepthCullingState = _DepthCullingState;
  5893. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5894. })(BABYLON || (BABYLON = {}));
  5895. var BABYLON;
  5896. (function (BABYLON) {
  5897. var Internals;
  5898. (function (Internals) {
  5899. var _StencilState = (function () {
  5900. function _StencilState() {
  5901. this._isStencilTestDirty = false;
  5902. this._isStencilMaskDirty = false;
  5903. this._isStencilFuncDirty = false;
  5904. this._isStencilOpDirty = false;
  5905. this.reset();
  5906. }
  5907. Object.defineProperty(_StencilState.prototype, "isDirty", {
  5908. get: function () {
  5909. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  5910. },
  5911. enumerable: true,
  5912. configurable: true
  5913. });
  5914. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  5915. get: function () {
  5916. return this._stencilFunc;
  5917. },
  5918. set: function (value) {
  5919. if (this._stencilFunc === value) {
  5920. return;
  5921. }
  5922. this._stencilFunc = value;
  5923. this._isStencilFuncDirty = true;
  5924. },
  5925. enumerable: true,
  5926. configurable: true
  5927. });
  5928. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  5929. get: function () {
  5930. return this._stencilFuncRef;
  5931. },
  5932. set: function (value) {
  5933. if (this._stencilFuncRef === value) {
  5934. return;
  5935. }
  5936. this._stencilFuncRef = value;
  5937. this._isStencilFuncDirty = true;
  5938. },
  5939. enumerable: true,
  5940. configurable: true
  5941. });
  5942. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  5943. get: function () {
  5944. return this._stencilFuncMask;
  5945. },
  5946. set: function (value) {
  5947. if (this._stencilFuncMask === value) {
  5948. return;
  5949. }
  5950. this._stencilFuncMask = value;
  5951. this._isStencilFuncDirty = true;
  5952. },
  5953. enumerable: true,
  5954. configurable: true
  5955. });
  5956. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  5957. get: function () {
  5958. return this._stencilOpStencilFail;
  5959. },
  5960. set: function (value) {
  5961. if (this._stencilOpStencilFail === value) {
  5962. return;
  5963. }
  5964. this._stencilOpStencilFail = value;
  5965. this._isStencilOpDirty = true;
  5966. },
  5967. enumerable: true,
  5968. configurable: true
  5969. });
  5970. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  5971. get: function () {
  5972. return this._stencilOpDepthFail;
  5973. },
  5974. set: function (value) {
  5975. if (this._stencilOpDepthFail === value) {
  5976. return;
  5977. }
  5978. this._stencilOpDepthFail = value;
  5979. this._isStencilOpDirty = true;
  5980. },
  5981. enumerable: true,
  5982. configurable: true
  5983. });
  5984. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  5985. get: function () {
  5986. return this._stencilOpStencilDepthPass;
  5987. },
  5988. set: function (value) {
  5989. if (this._stencilOpStencilDepthPass === value) {
  5990. return;
  5991. }
  5992. this._stencilOpStencilDepthPass = value;
  5993. this._isStencilOpDirty = true;
  5994. },
  5995. enumerable: true,
  5996. configurable: true
  5997. });
  5998. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  5999. get: function () {
  6000. return this._stencilMask;
  6001. },
  6002. set: function (value) {
  6003. if (this._stencilMask === value) {
  6004. return;
  6005. }
  6006. this._stencilMask = value;
  6007. this._isStencilMaskDirty = true;
  6008. },
  6009. enumerable: true,
  6010. configurable: true
  6011. });
  6012. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6013. get: function () {
  6014. return this._stencilTest;
  6015. },
  6016. set: function (value) {
  6017. if (this._stencilTest === value) {
  6018. return;
  6019. }
  6020. this._stencilTest = value;
  6021. this._isStencilTestDirty = true;
  6022. },
  6023. enumerable: true,
  6024. configurable: true
  6025. });
  6026. _StencilState.prototype.reset = function () {
  6027. this._stencilTest = false;
  6028. this._stencilMask = 0xFF;
  6029. this._stencilFunc = WebGLRenderingContext.ALWAYS;
  6030. this._stencilFuncRef = 1;
  6031. this._stencilFuncMask = 0xFF;
  6032. this._stencilOpStencilFail = WebGLRenderingContext.KEEP;
  6033. this._stencilOpDepthFail = WebGLRenderingContext.KEEP;
  6034. this._stencilOpStencilDepthPass = WebGLRenderingContext.REPLACE;
  6035. this._isStencilTestDirty = true;
  6036. this._isStencilMaskDirty = true;
  6037. this._isStencilFuncDirty = true;
  6038. this._isStencilOpDirty = true;
  6039. };
  6040. _StencilState.prototype.apply = function (gl) {
  6041. if (!this.isDirty) {
  6042. return;
  6043. }
  6044. // Stencil test
  6045. if (this._isStencilTestDirty) {
  6046. if (this.stencilTest) {
  6047. gl.enable(gl.STENCIL_TEST);
  6048. }
  6049. else {
  6050. gl.disable(gl.STENCIL_TEST);
  6051. }
  6052. this._isStencilTestDirty = false;
  6053. }
  6054. // Stencil mask
  6055. if (this._isStencilMaskDirty) {
  6056. gl.stencilMask(this.stencilMask);
  6057. this._isStencilMaskDirty = false;
  6058. }
  6059. // Stencil func
  6060. if (this._isStencilFuncDirty) {
  6061. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6062. this._isStencilFuncDirty = false;
  6063. }
  6064. // Stencil op
  6065. if (this._isStencilOpDirty) {
  6066. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6067. this._isStencilOpDirty = false;
  6068. }
  6069. };
  6070. return _StencilState;
  6071. }());
  6072. Internals._StencilState = _StencilState;
  6073. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6074. })(BABYLON || (BABYLON = {}));
  6075. var BABYLON;
  6076. (function (BABYLON) {
  6077. var compileShader = function (gl, source, type, defines) {
  6078. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6079. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6080. gl.compileShader(shader);
  6081. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6082. throw new Error(gl.getShaderInfoLog(shader));
  6083. }
  6084. return shader;
  6085. };
  6086. var HALF_FLOAT_OES = 0x8D61;
  6087. var getWebGLTextureType = function (gl, type) {
  6088. if (type === Engine.TEXTURETYPE_FLOAT) {
  6089. return gl.FLOAT;
  6090. }
  6091. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6092. // Add Half Float Constant.
  6093. return HALF_FLOAT_OES;
  6094. }
  6095. return gl.UNSIGNED_BYTE;
  6096. };
  6097. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6098. var magFilter = gl.NEAREST;
  6099. var minFilter = gl.NEAREST;
  6100. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6101. magFilter = gl.LINEAR;
  6102. if (generateMipMaps) {
  6103. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6104. }
  6105. else {
  6106. minFilter = gl.LINEAR;
  6107. }
  6108. }
  6109. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6110. magFilter = gl.LINEAR;
  6111. if (generateMipMaps) {
  6112. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6113. }
  6114. else {
  6115. minFilter = gl.LINEAR;
  6116. }
  6117. }
  6118. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6119. magFilter = gl.NEAREST;
  6120. if (generateMipMaps) {
  6121. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6122. }
  6123. else {
  6124. minFilter = gl.NEAREST;
  6125. }
  6126. }
  6127. return {
  6128. min: minFilter,
  6129. mag: magFilter
  6130. };
  6131. };
  6132. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6133. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6134. var engine = scene.getEngine();
  6135. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6136. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6137. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6138. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6139. texture._baseWidth = width;
  6140. texture._baseHeight = height;
  6141. texture._width = potWidth;
  6142. texture._height = potHeight;
  6143. texture.isReady = true;
  6144. processFunction(potWidth, potHeight);
  6145. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6146. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6147. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6148. if (!noMipmap && !isCompressed) {
  6149. gl.generateMipmap(gl.TEXTURE_2D);
  6150. }
  6151. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6152. engine.resetTextureCache();
  6153. scene._removePendingData(texture);
  6154. texture.onLoadedCallbacks.forEach(function (callback) {
  6155. callback();
  6156. });
  6157. texture.onLoadedCallbacks = [];
  6158. };
  6159. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  6160. var img;
  6161. var onload = function () {
  6162. loadedImages[index] = img;
  6163. loadedImages._internalCount++;
  6164. scene._removePendingData(img);
  6165. if (loadedImages._internalCount === 6) {
  6166. onfinish(loadedImages);
  6167. }
  6168. };
  6169. var onerror = function () {
  6170. scene._removePendingData(img);
  6171. };
  6172. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6173. scene._addPendingData(img);
  6174. };
  6175. var cascadeLoad = function (rootUrl, scene, onfinish, files) {
  6176. var loadedImages = [];
  6177. loadedImages._internalCount = 0;
  6178. for (var index = 0; index < 6; index++) {
  6179. partialLoad(files[index], index, loadedImages, scene, onfinish);
  6180. }
  6181. };
  6182. var InstancingAttributeInfo = (function () {
  6183. function InstancingAttributeInfo() {
  6184. }
  6185. return InstancingAttributeInfo;
  6186. }());
  6187. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6188. var EngineCapabilities = (function () {
  6189. function EngineCapabilities() {
  6190. }
  6191. return EngineCapabilities;
  6192. }());
  6193. BABYLON.EngineCapabilities = EngineCapabilities;
  6194. /**
  6195. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6196. */
  6197. var Engine = (function () {
  6198. /**
  6199. * @constructor
  6200. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6201. * @param {boolean} [antialias] - enable antialias
  6202. * @param options - further options to be sent to the getContext function
  6203. */
  6204. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6205. var _this = this;
  6206. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6207. // Public members
  6208. this.isFullscreen = false;
  6209. this.isPointerLock = false;
  6210. this.cullBackFaces = true;
  6211. this.renderEvenInBackground = true;
  6212. // To enable/disable IDB support and avoid XHR on .manifest
  6213. this.enableOfflineSupport = true;
  6214. this.scenes = new Array();
  6215. this._windowIsBackground = false;
  6216. this._webGLVersion = "1.0";
  6217. this._drawCalls = new BABYLON.PerfCounter();
  6218. this._renderingQueueLaunched = false;
  6219. this._activeRenderLoops = [];
  6220. // FPS
  6221. this.fpsRange = 60;
  6222. this.previousFramesDuration = [];
  6223. this.fps = 60;
  6224. this.deltaTime = 0;
  6225. // States
  6226. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6227. this._stencilState = new BABYLON.Internals._StencilState();
  6228. this._alphaState = new BABYLON.Internals._AlphaState();
  6229. this._alphaMode = Engine.ALPHA_DISABLE;
  6230. // Cache
  6231. this._loadedTexturesCache = new Array();
  6232. this._maxTextureChannels = 16;
  6233. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6234. this._compiledEffects = {};
  6235. this._vertexAttribArraysEnabled = [];
  6236. this._uintIndicesCurrentlySet = false;
  6237. this._currentBoundBuffer = new Array();
  6238. this._currentBufferPointers = [];
  6239. this._currentInstanceLocations = new Array();
  6240. this._currentInstanceBuffers = new Array();
  6241. this._onVRFullScreenTriggered = function () {
  6242. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6243. //get the old size before we change
  6244. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6245. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6246. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6247. //But actually, no browser follow the specs...
  6248. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6249. //get the width and height, change the render size
  6250. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6251. var width, height;
  6252. _this.setHardwareScalingLevel(1);
  6253. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6254. }
  6255. else {
  6256. //When the specs are implemented, need to uncomment this.
  6257. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6258. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6259. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6260. _this._vrDisplayEnabled = undefined;
  6261. }
  6262. };
  6263. this._renderingCanvas = canvas;
  6264. this._externalData = new BABYLON.StringDictionary();
  6265. options = options || {};
  6266. if (antialias != null) {
  6267. options.antialias = antialias;
  6268. }
  6269. if (options.preserveDrawingBuffer === undefined) {
  6270. options.preserveDrawingBuffer = false;
  6271. }
  6272. // Checks if some of the format renders first to allow the use of webgl inspector.
  6273. var renderToFullFloat = this._canRenderToFloatTexture();
  6274. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6275. // GL
  6276. //try {
  6277. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6278. // if (this._gl) {
  6279. // this._webGLVersion = "2.0";
  6280. // }
  6281. //} catch (e) {
  6282. // // Do nothing
  6283. //}
  6284. if (!this._gl) {
  6285. try {
  6286. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6287. }
  6288. catch (e) {
  6289. throw new Error("WebGL not supported");
  6290. }
  6291. }
  6292. if (!this._gl) {
  6293. throw new Error("WebGL not supported");
  6294. }
  6295. this._onBlur = function () {
  6296. _this._windowIsBackground = true;
  6297. };
  6298. this._onFocus = function () {
  6299. _this._windowIsBackground = false;
  6300. };
  6301. window.addEventListener("blur", this._onBlur);
  6302. window.addEventListener("focus", this._onFocus);
  6303. // Viewport
  6304. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6305. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6306. this.resize();
  6307. // Caps
  6308. this._isStencilEnable = options.stencil;
  6309. this._caps = new EngineCapabilities();
  6310. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6311. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6312. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6313. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6314. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6315. // Infos
  6316. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6317. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6318. if (rendererInfo != null) {
  6319. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6320. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6321. }
  6322. if (!this._glVendor) {
  6323. this._glVendor = "Unknown vendor";
  6324. }
  6325. if (!this._glRenderer) {
  6326. this._glRenderer = "Unknown renderer";
  6327. }
  6328. // Extensions
  6329. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6330. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6331. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6332. 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');
  6333. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6334. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6335. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6336. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6337. this._caps.highPrecisionShaderSupported = true;
  6338. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6339. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6340. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6341. this._caps.textureFloatRender = renderToFullFloat;
  6342. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6343. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6344. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6345. if (this._gl.getShaderPrecisionFormat) {
  6346. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6347. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6348. }
  6349. // Depth buffer
  6350. this.setDepthBuffer(true);
  6351. this.setDepthFunctionToLessOrEqual();
  6352. this.setDepthWrite(true);
  6353. // Fullscreen
  6354. this._onFullscreenChange = function () {
  6355. if (document.fullscreen !== undefined) {
  6356. _this.isFullscreen = document.fullscreen;
  6357. }
  6358. else if (document.mozFullScreen !== undefined) {
  6359. _this.isFullscreen = document.mozFullScreen;
  6360. }
  6361. else if (document.webkitIsFullScreen !== undefined) {
  6362. _this.isFullscreen = document.webkitIsFullScreen;
  6363. }
  6364. else if (document.msIsFullScreen !== undefined) {
  6365. _this.isFullscreen = document.msIsFullScreen;
  6366. }
  6367. // Pointer lock
  6368. if (_this.isFullscreen && _this._pointerLockRequested) {
  6369. canvas.requestPointerLock = canvas.requestPointerLock ||
  6370. canvas.msRequestPointerLock ||
  6371. canvas.mozRequestPointerLock ||
  6372. canvas.webkitRequestPointerLock;
  6373. if (canvas.requestPointerLock) {
  6374. canvas.requestPointerLock();
  6375. }
  6376. }
  6377. };
  6378. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6379. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6380. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6381. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6382. // Pointer lock
  6383. this._onPointerLockChange = function () {
  6384. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6385. document.webkitPointerLockElement === canvas ||
  6386. document.msPointerLockElement === canvas ||
  6387. document.pointerLockElement === canvas);
  6388. };
  6389. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6390. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6391. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6392. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6393. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6394. Engine.audioEngine = new BABYLON.AudioEngine();
  6395. }
  6396. //default loading screen
  6397. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6398. //Load WebVR Devices
  6399. if (options.autoEnableWebVR) {
  6400. this.initWebVR();
  6401. }
  6402. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6403. }
  6404. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6405. get: function () {
  6406. return Engine._ALPHA_DISABLE;
  6407. },
  6408. enumerable: true,
  6409. configurable: true
  6410. });
  6411. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6412. get: function () {
  6413. return Engine._ALPHA_ONEONE;
  6414. },
  6415. enumerable: true,
  6416. configurable: true
  6417. });
  6418. Object.defineProperty(Engine, "ALPHA_ADD", {
  6419. get: function () {
  6420. return Engine._ALPHA_ADD;
  6421. },
  6422. enumerable: true,
  6423. configurable: true
  6424. });
  6425. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6426. get: function () {
  6427. return Engine._ALPHA_COMBINE;
  6428. },
  6429. enumerable: true,
  6430. configurable: true
  6431. });
  6432. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6433. get: function () {
  6434. return Engine._ALPHA_SUBTRACT;
  6435. },
  6436. enumerable: true,
  6437. configurable: true
  6438. });
  6439. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6440. get: function () {
  6441. return Engine._ALPHA_MULTIPLY;
  6442. },
  6443. enumerable: true,
  6444. configurable: true
  6445. });
  6446. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6447. get: function () {
  6448. return Engine._ALPHA_MAXIMIZED;
  6449. },
  6450. enumerable: true,
  6451. configurable: true
  6452. });
  6453. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6454. get: function () {
  6455. return Engine._DELAYLOADSTATE_NONE;
  6456. },
  6457. enumerable: true,
  6458. configurable: true
  6459. });
  6460. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6461. get: function () {
  6462. return Engine._DELAYLOADSTATE_LOADED;
  6463. },
  6464. enumerable: true,
  6465. configurable: true
  6466. });
  6467. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6468. get: function () {
  6469. return Engine._DELAYLOADSTATE_LOADING;
  6470. },
  6471. enumerable: true,
  6472. configurable: true
  6473. });
  6474. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6475. get: function () {
  6476. return Engine._DELAYLOADSTATE_NOTLOADED;
  6477. },
  6478. enumerable: true,
  6479. configurable: true
  6480. });
  6481. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6482. get: function () {
  6483. return Engine._TEXTUREFORMAT_ALPHA;
  6484. },
  6485. enumerable: true,
  6486. configurable: true
  6487. });
  6488. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6489. get: function () {
  6490. return Engine._TEXTUREFORMAT_LUMINANCE;
  6491. },
  6492. enumerable: true,
  6493. configurable: true
  6494. });
  6495. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6496. get: function () {
  6497. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6498. },
  6499. enumerable: true,
  6500. configurable: true
  6501. });
  6502. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6503. get: function () {
  6504. return Engine._TEXTUREFORMAT_RGB;
  6505. },
  6506. enumerable: true,
  6507. configurable: true
  6508. });
  6509. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6510. get: function () {
  6511. return Engine._TEXTUREFORMAT_RGBA;
  6512. },
  6513. enumerable: true,
  6514. configurable: true
  6515. });
  6516. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6517. get: function () {
  6518. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6519. },
  6520. enumerable: true,
  6521. configurable: true
  6522. });
  6523. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6524. get: function () {
  6525. return Engine._TEXTURETYPE_FLOAT;
  6526. },
  6527. enumerable: true,
  6528. configurable: true
  6529. });
  6530. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6531. get: function () {
  6532. return Engine._TEXTURETYPE_HALF_FLOAT;
  6533. },
  6534. enumerable: true,
  6535. configurable: true
  6536. });
  6537. Object.defineProperty(Engine, "Version", {
  6538. get: function () {
  6539. return "2.5-alpha";
  6540. },
  6541. enumerable: true,
  6542. configurable: true
  6543. });
  6544. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6545. get: function () {
  6546. return this._webGLVersion;
  6547. },
  6548. enumerable: true,
  6549. configurable: true
  6550. });
  6551. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6552. /**
  6553. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6554. */
  6555. get: function () {
  6556. return this._isStencilEnable;
  6557. },
  6558. enumerable: true,
  6559. configurable: true
  6560. });
  6561. Engine.prototype._prepareWorkingCanvas = function () {
  6562. if (this._workingCanvas) {
  6563. return;
  6564. }
  6565. this._workingCanvas = document.createElement("canvas");
  6566. this._workingContext = this._workingCanvas.getContext("2d");
  6567. };
  6568. Engine.prototype.resetTextureCache = function () {
  6569. for (var index = 0; index < this._maxTextureChannels; index++) {
  6570. this._activeTexturesCache[index] = null;
  6571. }
  6572. };
  6573. Engine.prototype.getGlInfo = function () {
  6574. return {
  6575. vendor: this._glVendor,
  6576. renderer: this._glRenderer,
  6577. version: this._glVersion
  6578. };
  6579. };
  6580. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6581. if (useScreen === void 0) { useScreen = false; }
  6582. var viewport = camera.viewport;
  6583. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6584. };
  6585. Engine.prototype.getRenderWidth = function (useScreen) {
  6586. if (useScreen === void 0) { useScreen = false; }
  6587. if (!useScreen && this._currentRenderTarget) {
  6588. return this._currentRenderTarget._width;
  6589. }
  6590. return this._renderingCanvas.width;
  6591. };
  6592. Engine.prototype.getRenderHeight = function (useScreen) {
  6593. if (useScreen === void 0) { useScreen = false; }
  6594. if (!useScreen && this._currentRenderTarget) {
  6595. return this._currentRenderTarget._height;
  6596. }
  6597. return this._renderingCanvas.height;
  6598. };
  6599. Engine.prototype.getRenderingCanvas = function () {
  6600. return this._renderingCanvas;
  6601. };
  6602. Engine.prototype.getRenderingCanvasClientRect = function () {
  6603. return this._renderingCanvas.getBoundingClientRect();
  6604. };
  6605. Engine.prototype.setHardwareScalingLevel = function (level) {
  6606. this._hardwareScalingLevel = level;
  6607. this.resize();
  6608. };
  6609. Engine.prototype.getHardwareScalingLevel = function () {
  6610. return this._hardwareScalingLevel;
  6611. };
  6612. Engine.prototype.getLoadedTexturesCache = function () {
  6613. return this._loadedTexturesCache;
  6614. };
  6615. Engine.prototype.getCaps = function () {
  6616. return this._caps;
  6617. };
  6618. Object.defineProperty(Engine.prototype, "drawCalls", {
  6619. get: function () {
  6620. return this._drawCalls.current;
  6621. },
  6622. enumerable: true,
  6623. configurable: true
  6624. });
  6625. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6626. get: function () {
  6627. return this._drawCalls;
  6628. },
  6629. enumerable: true,
  6630. configurable: true
  6631. });
  6632. Engine.prototype.getDepthFunction = function () {
  6633. return this._depthCullingState.depthFunc;
  6634. };
  6635. Engine.prototype.setDepthFunction = function (depthFunc) {
  6636. this._depthCullingState.depthFunc = depthFunc;
  6637. };
  6638. Engine.prototype.setDepthFunctionToGreater = function () {
  6639. this._depthCullingState.depthFunc = this._gl.GREATER;
  6640. };
  6641. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6642. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6643. };
  6644. Engine.prototype.setDepthFunctionToLess = function () {
  6645. this._depthCullingState.depthFunc = this._gl.LESS;
  6646. };
  6647. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6648. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6649. };
  6650. Engine.prototype.getStencilBuffer = function () {
  6651. return this._stencilState.stencilTest;
  6652. };
  6653. Engine.prototype.setStencilBuffer = function (enable) {
  6654. this._stencilState.stencilTest = enable;
  6655. };
  6656. Engine.prototype.getStencilMask = function () {
  6657. return this._stencilState.stencilMask;
  6658. };
  6659. Engine.prototype.setStencilMask = function (mask) {
  6660. this._stencilState.stencilMask = mask;
  6661. };
  6662. Engine.prototype.getStencilFunction = function () {
  6663. return this._stencilState.stencilFunc;
  6664. };
  6665. Engine.prototype.getStencilFunctionReference = function () {
  6666. return this._stencilState.stencilFuncRef;
  6667. };
  6668. Engine.prototype.getStencilFunctionMask = function () {
  6669. return this._stencilState.stencilFuncMask;
  6670. };
  6671. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6672. this._stencilState.stencilFunc = stencilFunc;
  6673. };
  6674. Engine.prototype.setStencilFunctionReference = function (reference) {
  6675. this._stencilState.stencilFuncRef = reference;
  6676. };
  6677. Engine.prototype.setStencilFunctionMask = function (mask) {
  6678. this._stencilState.stencilFuncMask = mask;
  6679. };
  6680. Engine.prototype.getStencilOperationFail = function () {
  6681. return this._stencilState.stencilOpStencilFail;
  6682. };
  6683. Engine.prototype.getStencilOperationDepthFail = function () {
  6684. return this._stencilState.stencilOpDepthFail;
  6685. };
  6686. Engine.prototype.getStencilOperationPass = function () {
  6687. return this._stencilState.stencilOpStencilDepthPass;
  6688. };
  6689. Engine.prototype.setStencilOperationFail = function (operation) {
  6690. this._stencilState.stencilOpStencilFail = operation;
  6691. };
  6692. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6693. this._stencilState.stencilOpDepthFail = operation;
  6694. };
  6695. Engine.prototype.setStencilOperationPass = function (operation) {
  6696. this._stencilState.stencilOpStencilDepthPass = operation;
  6697. };
  6698. /**
  6699. * stop executing a render loop function and remove it from the execution array
  6700. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6701. */
  6702. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6703. if (!renderFunction) {
  6704. this._activeRenderLoops = [];
  6705. return;
  6706. }
  6707. var index = this._activeRenderLoops.indexOf(renderFunction);
  6708. if (index >= 0) {
  6709. this._activeRenderLoops.splice(index, 1);
  6710. }
  6711. };
  6712. Engine.prototype._renderLoop = function () {
  6713. var shouldRender = true;
  6714. if (!this.renderEvenInBackground && this._windowIsBackground) {
  6715. shouldRender = false;
  6716. }
  6717. if (shouldRender) {
  6718. // Start new frame
  6719. this.beginFrame();
  6720. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  6721. var renderFunction = this._activeRenderLoops[index];
  6722. renderFunction();
  6723. }
  6724. // Present
  6725. this.endFrame();
  6726. }
  6727. if (this._activeRenderLoops.length > 0) {
  6728. // Register new frame
  6729. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  6730. }
  6731. else {
  6732. this._renderingQueueLaunched = false;
  6733. }
  6734. };
  6735. /**
  6736. * Register and execute a render loop. The engine can have more than one render function.
  6737. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  6738. * @example
  6739. * engine.runRenderLoop(function () {
  6740. * scene.render()
  6741. * })
  6742. */
  6743. Engine.prototype.runRenderLoop = function (renderFunction) {
  6744. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  6745. return;
  6746. }
  6747. this._activeRenderLoops.push(renderFunction);
  6748. if (!this._renderingQueueLaunched) {
  6749. this._renderingQueueLaunched = true;
  6750. this._bindedRenderFunction = this._renderLoop.bind(this);
  6751. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  6752. }
  6753. };
  6754. /**
  6755. * Toggle full screen mode.
  6756. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  6757. * @param {any} options - an options object to be sent to the requestFullscreen function
  6758. */
  6759. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  6760. if (this.isFullscreen) {
  6761. BABYLON.Tools.ExitFullscreen();
  6762. }
  6763. else {
  6764. this._pointerLockRequested = requestPointerLock;
  6765. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  6766. }
  6767. };
  6768. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  6769. if (stencil === void 0) { stencil = false; }
  6770. this.applyStates();
  6771. var mode = 0;
  6772. if (backBuffer) {
  6773. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  6774. mode |= this._gl.COLOR_BUFFER_BIT;
  6775. }
  6776. if (depth) {
  6777. this._gl.clearDepth(1.0);
  6778. mode |= this._gl.DEPTH_BUFFER_BIT;
  6779. }
  6780. if (stencil) {
  6781. this._gl.clearStencil(0);
  6782. mode |= this._gl.STENCIL_BUFFER_BIT;
  6783. }
  6784. this._gl.clear(mode);
  6785. };
  6786. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  6787. var gl = this._gl;
  6788. // Save state
  6789. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  6790. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  6791. // Change state
  6792. gl.enable(gl.SCISSOR_TEST);
  6793. gl.scissor(x, y, width, height);
  6794. // Clear
  6795. this.clear(clearColor, true, true, true);
  6796. // Restore state
  6797. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  6798. if (curScissor === true) {
  6799. gl.enable(gl.SCISSOR_TEST);
  6800. }
  6801. else {
  6802. gl.disable(gl.SCISSOR_TEST);
  6803. }
  6804. };
  6805. /**
  6806. * Set the WebGL's viewport
  6807. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  6808. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  6809. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  6810. */
  6811. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  6812. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  6813. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  6814. var x = viewport.x || 0;
  6815. var y = viewport.y || 0;
  6816. this._cachedViewport = viewport;
  6817. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  6818. };
  6819. /**
  6820. * Directly set the WebGL Viewport
  6821. * The x, y, width & height are directly passed to the WebGL call
  6822. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  6823. */
  6824. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  6825. var currentViewport = this._cachedViewport;
  6826. this._cachedViewport = null;
  6827. this._gl.viewport(x, y, width, height);
  6828. return currentViewport;
  6829. };
  6830. Engine.prototype.beginFrame = function () {
  6831. this._measureFps();
  6832. };
  6833. Engine.prototype.endFrame = function () {
  6834. //this.flushFramebuffer();
  6835. //submit frame to the vr device, if enabled
  6836. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  6837. this._vrDisplayEnabled.submitFrame();
  6838. }
  6839. };
  6840. /**
  6841. * resize the view according to the canvas' size.
  6842. * @example
  6843. * window.addEventListener("resize", function () {
  6844. * engine.resize();
  6845. * });
  6846. */
  6847. Engine.prototype.resize = function () {
  6848. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  6849. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  6850. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  6851. for (var index = 0; index < this.scenes.length; index++) {
  6852. var scene = this.scenes[index];
  6853. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  6854. scene.debugLayer._syncPositions();
  6855. }
  6856. }
  6857. };
  6858. /**
  6859. * force a specific size of the canvas
  6860. * @param {number} width - the new canvas' width
  6861. * @param {number} height - the new canvas' height
  6862. */
  6863. Engine.prototype.setSize = function (width, height) {
  6864. this._renderingCanvas.width = width;
  6865. this._renderingCanvas.height = height;
  6866. for (var index = 0; index < this.scenes.length; index++) {
  6867. var scene = this.scenes[index];
  6868. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  6869. var cam = scene.cameras[camIndex];
  6870. cam._currentRenderId = 0;
  6871. }
  6872. }
  6873. };
  6874. //WebVR functions
  6875. Engine.prototype.initWebVR = function () {
  6876. if (!this.vrDisplaysPromise) {
  6877. this._getVRDisplays();
  6878. }
  6879. };
  6880. Engine.prototype.enableVR = function (vrDevice) {
  6881. this._vrDisplayEnabled = vrDevice;
  6882. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  6883. };
  6884. Engine.prototype.disableVR = function () {
  6885. if (this._vrDisplayEnabled) {
  6886. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  6887. }
  6888. };
  6889. Engine.prototype._getVRDisplays = function () {
  6890. var _this = this;
  6891. var getWebVRDevices = function (devices) {
  6892. var size = devices.length;
  6893. var i = 0;
  6894. _this._vrDisplays = devices.filter(function (device) {
  6895. return devices[i] instanceof VRDisplay;
  6896. });
  6897. return _this._vrDisplays;
  6898. };
  6899. //using a key due to typescript
  6900. if (navigator.getVRDisplays) {
  6901. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  6902. }
  6903. };
  6904. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  6905. this._currentRenderTarget = texture;
  6906. this.bindUnboundFramebuffer(texture._framebuffer);
  6907. var gl = this._gl;
  6908. if (texture.isCube) {
  6909. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  6910. }
  6911. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  6912. this.wipeCaches();
  6913. };
  6914. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  6915. if (this._currentFramebuffer !== framebuffer) {
  6916. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  6917. this._currentFramebuffer = framebuffer;
  6918. }
  6919. };
  6920. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  6921. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  6922. this._currentRenderTarget = null;
  6923. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  6924. var gl = this._gl;
  6925. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6926. gl.generateMipmap(gl.TEXTURE_2D);
  6927. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  6928. }
  6929. this.bindUnboundFramebuffer(null);
  6930. };
  6931. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  6932. if (texture.generateMipMaps) {
  6933. var gl = this._gl;
  6934. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  6935. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6936. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  6937. }
  6938. };
  6939. Engine.prototype.flushFramebuffer = function () {
  6940. this._gl.flush();
  6941. };
  6942. Engine.prototype.restoreDefaultFramebuffer = function () {
  6943. this._currentRenderTarget = null;
  6944. this.bindUnboundFramebuffer(null);
  6945. this.setViewport(this._cachedViewport);
  6946. this.wipeCaches();
  6947. };
  6948. // VBOs
  6949. Engine.prototype._resetVertexBufferBinding = function () {
  6950. this.bindArrayBuffer(null);
  6951. this._cachedVertexBuffers = null;
  6952. };
  6953. Engine.prototype.createVertexBuffer = function (vertices) {
  6954. var vbo = this._gl.createBuffer();
  6955. this.bindArrayBuffer(vbo);
  6956. if (vertices instanceof Float32Array) {
  6957. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  6958. }
  6959. else {
  6960. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  6961. }
  6962. this._resetVertexBufferBinding();
  6963. vbo.references = 1;
  6964. return vbo;
  6965. };
  6966. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  6967. var vbo = this._gl.createBuffer();
  6968. this.bindArrayBuffer(vbo);
  6969. if (vertices instanceof Float32Array) {
  6970. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  6971. }
  6972. else {
  6973. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  6974. }
  6975. this._resetVertexBufferBinding();
  6976. vbo.references = 1;
  6977. return vbo;
  6978. };
  6979. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  6980. this.bindArrayBuffer(vertexBuffer);
  6981. if (offset === undefined) {
  6982. offset = 0;
  6983. }
  6984. if (count === undefined) {
  6985. if (vertices instanceof Float32Array) {
  6986. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  6987. }
  6988. else {
  6989. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  6990. }
  6991. }
  6992. else {
  6993. if (vertices instanceof Float32Array) {
  6994. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  6995. }
  6996. else {
  6997. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  6998. }
  6999. }
  7000. this._resetVertexBufferBinding();
  7001. };
  7002. Engine.prototype._resetIndexBufferBinding = function () {
  7003. this.bindIndexBuffer(null);
  7004. this._cachedIndexBuffer = null;
  7005. };
  7006. Engine.prototype.createIndexBuffer = function (indices) {
  7007. var vbo = this._gl.createBuffer();
  7008. this.bindIndexBuffer(vbo);
  7009. // Check for 32 bits indices
  7010. var arrayBuffer;
  7011. var need32Bits = false;
  7012. if (this._caps.uintIndices) {
  7013. for (var index = 0; index < indices.length; index++) {
  7014. if (indices[index] > 65535) {
  7015. need32Bits = true;
  7016. break;
  7017. }
  7018. }
  7019. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7020. }
  7021. else {
  7022. arrayBuffer = new Uint16Array(indices);
  7023. }
  7024. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7025. this._resetIndexBufferBinding();
  7026. vbo.references = 1;
  7027. vbo.is32Bits = need32Bits;
  7028. return vbo;
  7029. };
  7030. Engine.prototype.bindArrayBuffer = function (buffer) {
  7031. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7032. };
  7033. Engine.prototype.bindIndexBuffer = function (buffer) {
  7034. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7035. };
  7036. Engine.prototype.bindBuffer = function (buffer, target) {
  7037. if (this._currentBoundBuffer[target] !== buffer) {
  7038. this._gl.bindBuffer(target, buffer);
  7039. this._currentBoundBuffer[target] = buffer;
  7040. }
  7041. };
  7042. Engine.prototype.updateArrayBuffer = function (data) {
  7043. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7044. };
  7045. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7046. var pointer = this._currentBufferPointers[indx];
  7047. var changed = false;
  7048. if (!pointer) {
  7049. changed = true;
  7050. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7051. }
  7052. else {
  7053. if (pointer.buffer !== buffer) {
  7054. pointer.buffer = buffer;
  7055. changed = true;
  7056. }
  7057. if (pointer.size !== size) {
  7058. pointer.size = size;
  7059. changed = true;
  7060. }
  7061. if (pointer.type !== type) {
  7062. pointer.type = type;
  7063. changed = true;
  7064. }
  7065. if (pointer.normalized !== normalized) {
  7066. pointer.normalized = normalized;
  7067. changed = true;
  7068. }
  7069. if (pointer.stride !== stride) {
  7070. pointer.stride = stride;
  7071. changed = true;
  7072. }
  7073. if (pointer.offset !== offset) {
  7074. pointer.offset = offset;
  7075. changed = true;
  7076. }
  7077. }
  7078. if (changed) {
  7079. this.bindArrayBuffer(buffer);
  7080. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7081. }
  7082. };
  7083. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7084. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7085. this._cachedVertexBuffers = vertexBuffer;
  7086. this._cachedEffectForVertexBuffers = effect;
  7087. var attributesCount = effect.getAttributesCount();
  7088. var offset = 0;
  7089. for (var index = 0; index < attributesCount; index++) {
  7090. if (index < vertexDeclaration.length) {
  7091. var order = effect.getAttributeLocation(index);
  7092. if (order >= 0) {
  7093. if (!this._vertexAttribArraysEnabled[order]) {
  7094. this._gl.enableVertexAttribArray(order);
  7095. this._vertexAttribArraysEnabled[order] = true;
  7096. }
  7097. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7098. }
  7099. offset += vertexDeclaration[index] * 4;
  7100. }
  7101. else {
  7102. //disable effect attributes that have no data
  7103. var order = effect.getAttributeLocation(index);
  7104. if (this._vertexAttribArraysEnabled[order]) {
  7105. this._gl.disableVertexAttribArray(order);
  7106. this._vertexAttribArraysEnabled[order] = false;
  7107. }
  7108. }
  7109. }
  7110. }
  7111. if (this._cachedIndexBuffer !== indexBuffer) {
  7112. this._cachedIndexBuffer = indexBuffer;
  7113. this.bindIndexBuffer(indexBuffer);
  7114. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7115. }
  7116. };
  7117. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7118. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7119. this._cachedVertexBuffers = vertexBuffers;
  7120. this._cachedEffectForVertexBuffers = effect;
  7121. var attributes = effect.getAttributesNames();
  7122. for (var index = 0; index < attributes.length; index++) {
  7123. var order = effect.getAttributeLocation(index);
  7124. if (order >= 0) {
  7125. var vertexBuffer = vertexBuffers[attributes[index]];
  7126. if (!vertexBuffer) {
  7127. if (this._vertexAttribArraysEnabled[order]) {
  7128. this._gl.disableVertexAttribArray(order);
  7129. this._vertexAttribArraysEnabled[order] = false;
  7130. }
  7131. continue;
  7132. }
  7133. if (!this._vertexAttribArraysEnabled[order]) {
  7134. this._gl.enableVertexAttribArray(order);
  7135. this._vertexAttribArraysEnabled[order] = true;
  7136. }
  7137. var buffer = vertexBuffer.getBuffer();
  7138. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7139. if (vertexBuffer.getIsInstanced()) {
  7140. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7141. this._currentInstanceLocations.push(order);
  7142. this._currentInstanceBuffers.push(buffer);
  7143. }
  7144. }
  7145. }
  7146. }
  7147. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7148. this._cachedIndexBuffer = indexBuffer;
  7149. this.bindIndexBuffer(indexBuffer);
  7150. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7151. }
  7152. };
  7153. Engine.prototype.unbindInstanceAttributes = function () {
  7154. var boundBuffer;
  7155. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7156. var instancesBuffer = this._currentInstanceBuffers[i];
  7157. if (boundBuffer != instancesBuffer) {
  7158. boundBuffer = instancesBuffer;
  7159. this.bindArrayBuffer(instancesBuffer);
  7160. }
  7161. var offsetLocation = this._currentInstanceLocations[i];
  7162. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7163. }
  7164. this._currentInstanceBuffers.length = 0;
  7165. this._currentInstanceLocations.length = 0;
  7166. };
  7167. Engine.prototype._releaseBuffer = function (buffer) {
  7168. buffer.references--;
  7169. if (buffer.references === 0) {
  7170. this._gl.deleteBuffer(buffer);
  7171. return true;
  7172. }
  7173. return false;
  7174. };
  7175. Engine.prototype.createInstancesBuffer = function (capacity) {
  7176. var buffer = this._gl.createBuffer();
  7177. buffer.capacity = capacity;
  7178. this.bindArrayBuffer(buffer);
  7179. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7180. return buffer;
  7181. };
  7182. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7183. this._gl.deleteBuffer(buffer);
  7184. };
  7185. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7186. this.bindArrayBuffer(instancesBuffer);
  7187. if (data) {
  7188. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7189. }
  7190. if (offsetLocations[0].index !== undefined) {
  7191. var stride = 0;
  7192. for (var i = 0; i < offsetLocations.length; i++) {
  7193. var ai = offsetLocations[i];
  7194. stride += ai.attributeSize * 4;
  7195. }
  7196. for (var i = 0; i < offsetLocations.length; i++) {
  7197. var ai = offsetLocations[i];
  7198. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7199. this._gl.enableVertexAttribArray(ai.index);
  7200. this._vertexAttribArraysEnabled[ai.index] = true;
  7201. }
  7202. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7203. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7204. this._currentInstanceLocations.push(ai.index);
  7205. this._currentInstanceBuffers.push(instancesBuffer);
  7206. }
  7207. }
  7208. else {
  7209. for (var index = 0; index < 4; index++) {
  7210. var offsetLocation = offsetLocations[index];
  7211. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7212. this._gl.enableVertexAttribArray(offsetLocation);
  7213. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7214. }
  7215. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7216. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7217. this._currentInstanceLocations.push(offsetLocation);
  7218. this._currentInstanceBuffers.push(instancesBuffer);
  7219. }
  7220. }
  7221. };
  7222. Engine.prototype.applyStates = function () {
  7223. this._depthCullingState.apply(this._gl);
  7224. this._stencilState.apply(this._gl);
  7225. this._alphaState.apply(this._gl);
  7226. };
  7227. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7228. // Apply states
  7229. this.applyStates();
  7230. this._drawCalls.addCount(1, false);
  7231. // Render
  7232. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7233. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7234. if (instancesCount) {
  7235. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7236. return;
  7237. }
  7238. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7239. };
  7240. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7241. // Apply states
  7242. this.applyStates();
  7243. this._drawCalls.addCount(1, false);
  7244. if (instancesCount) {
  7245. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7246. return;
  7247. }
  7248. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7249. };
  7250. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7251. // Apply states
  7252. this.applyStates();
  7253. this._drawCalls.addCount(1, false);
  7254. if (instancesCount) {
  7255. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7256. return;
  7257. }
  7258. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7259. };
  7260. // Shaders
  7261. Engine.prototype._releaseEffect = function (effect) {
  7262. if (this._compiledEffects[effect._key]) {
  7263. delete this._compiledEffects[effect._key];
  7264. if (effect.getProgram()) {
  7265. this._gl.deleteProgram(effect.getProgram());
  7266. }
  7267. }
  7268. };
  7269. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7270. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7271. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7272. var name = vertex + "+" + fragment + "@" + defines;
  7273. if (this._compiledEffects[name]) {
  7274. return this._compiledEffects[name];
  7275. }
  7276. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7277. effect._key = name;
  7278. this._compiledEffects[name] = effect;
  7279. return effect;
  7280. };
  7281. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7282. if (uniformsNames === void 0) { uniformsNames = []; }
  7283. if (samplers === void 0) { samplers = []; }
  7284. if (defines === void 0) { defines = ""; }
  7285. return this.createEffect({
  7286. vertex: "particles",
  7287. fragmentElement: fragmentName
  7288. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7289. };
  7290. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7291. context = context || this._gl;
  7292. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7293. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7294. var shaderProgram = context.createProgram();
  7295. context.attachShader(shaderProgram, vertexShader);
  7296. context.attachShader(shaderProgram, fragmentShader);
  7297. context.linkProgram(shaderProgram);
  7298. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7299. if (!linked) {
  7300. var error = context.getProgramInfoLog(shaderProgram);
  7301. if (error) {
  7302. throw new Error(error);
  7303. }
  7304. }
  7305. context.deleteShader(vertexShader);
  7306. context.deleteShader(fragmentShader);
  7307. return shaderProgram;
  7308. };
  7309. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7310. var results = [];
  7311. for (var index = 0; index < uniformsNames.length; index++) {
  7312. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7313. }
  7314. return results;
  7315. };
  7316. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7317. var results = [];
  7318. for (var index = 0; index < attributesNames.length; index++) {
  7319. try {
  7320. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7321. }
  7322. catch (e) {
  7323. results.push(-1);
  7324. }
  7325. }
  7326. return results;
  7327. };
  7328. Engine.prototype.enableEffect = function (effect) {
  7329. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7330. if (effect && effect.onBind) {
  7331. effect.onBind(effect);
  7332. }
  7333. return;
  7334. }
  7335. // Use program
  7336. this.setProgram(effect.getProgram());
  7337. this._currentEffect = effect;
  7338. if (effect.onBind) {
  7339. effect.onBind(effect);
  7340. }
  7341. };
  7342. Engine.prototype.setIntArray = function (uniform, array) {
  7343. if (!uniform)
  7344. return;
  7345. this._gl.uniform1iv(uniform, array);
  7346. };
  7347. Engine.prototype.setIntArray2 = function (uniform, array) {
  7348. if (!uniform || array.length % 2 !== 0)
  7349. return;
  7350. this._gl.uniform2iv(uniform, array);
  7351. };
  7352. Engine.prototype.setIntArray3 = function (uniform, array) {
  7353. if (!uniform || array.length % 3 !== 0)
  7354. return;
  7355. this._gl.uniform3iv(uniform, array);
  7356. };
  7357. Engine.prototype.setIntArray4 = function (uniform, array) {
  7358. if (!uniform || array.length % 4 !== 0)
  7359. return;
  7360. this._gl.uniform4iv(uniform, array);
  7361. };
  7362. Engine.prototype.setFloatArray = function (uniform, array) {
  7363. if (!uniform)
  7364. return;
  7365. this._gl.uniform1fv(uniform, array);
  7366. };
  7367. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7368. if (!uniform || array.length % 2 !== 0)
  7369. return;
  7370. this._gl.uniform2fv(uniform, array);
  7371. };
  7372. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7373. if (!uniform || array.length % 3 !== 0)
  7374. return;
  7375. this._gl.uniform3fv(uniform, array);
  7376. };
  7377. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7378. if (!uniform || array.length % 4 !== 0)
  7379. return;
  7380. this._gl.uniform4fv(uniform, array);
  7381. };
  7382. Engine.prototype.setArray = function (uniform, array) {
  7383. if (!uniform)
  7384. return;
  7385. this._gl.uniform1fv(uniform, array);
  7386. };
  7387. Engine.prototype.setArray2 = function (uniform, array) {
  7388. if (!uniform || array.length % 2 !== 0)
  7389. return;
  7390. this._gl.uniform2fv(uniform, array);
  7391. };
  7392. Engine.prototype.setArray3 = function (uniform, array) {
  7393. if (!uniform || array.length % 3 !== 0)
  7394. return;
  7395. this._gl.uniform3fv(uniform, array);
  7396. };
  7397. Engine.prototype.setArray4 = function (uniform, array) {
  7398. if (!uniform || array.length % 4 !== 0)
  7399. return;
  7400. this._gl.uniform4fv(uniform, array);
  7401. };
  7402. Engine.prototype.setMatrices = function (uniform, matrices) {
  7403. if (!uniform)
  7404. return;
  7405. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7406. };
  7407. Engine.prototype.setMatrix = function (uniform, matrix) {
  7408. if (!uniform)
  7409. return;
  7410. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7411. };
  7412. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7413. if (!uniform)
  7414. return;
  7415. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7416. };
  7417. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7418. if (!uniform)
  7419. return;
  7420. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7421. };
  7422. Engine.prototype.setFloat = function (uniform, value) {
  7423. if (!uniform)
  7424. return;
  7425. this._gl.uniform1f(uniform, value);
  7426. };
  7427. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7428. if (!uniform)
  7429. return;
  7430. this._gl.uniform2f(uniform, x, y);
  7431. };
  7432. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7433. if (!uniform)
  7434. return;
  7435. this._gl.uniform3f(uniform, x, y, z);
  7436. };
  7437. Engine.prototype.setBool = function (uniform, bool) {
  7438. if (!uniform)
  7439. return;
  7440. this._gl.uniform1i(uniform, bool);
  7441. };
  7442. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7443. if (!uniform)
  7444. return;
  7445. this._gl.uniform4f(uniform, x, y, z, w);
  7446. };
  7447. Engine.prototype.setColor3 = function (uniform, color3) {
  7448. if (!uniform)
  7449. return;
  7450. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7451. };
  7452. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7453. if (!uniform)
  7454. return;
  7455. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7456. };
  7457. // States
  7458. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7459. if (zOffset === void 0) { zOffset = 0; }
  7460. if (reverseSide === void 0) { reverseSide = false; }
  7461. // Culling
  7462. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7463. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7464. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7465. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7466. if (culling) {
  7467. this._depthCullingState.cullFace = cullFace;
  7468. this._depthCullingState.cull = true;
  7469. }
  7470. else {
  7471. this._depthCullingState.cull = false;
  7472. }
  7473. }
  7474. // Z offset
  7475. this._depthCullingState.zOffset = zOffset;
  7476. };
  7477. Engine.prototype.setDepthBuffer = function (enable) {
  7478. this._depthCullingState.depthTest = enable;
  7479. };
  7480. Engine.prototype.getDepthWrite = function () {
  7481. return this._depthCullingState.depthMask;
  7482. };
  7483. Engine.prototype.setDepthWrite = function (enable) {
  7484. this._depthCullingState.depthMask = enable;
  7485. };
  7486. Engine.prototype.setColorWrite = function (enable) {
  7487. this._gl.colorMask(enable, enable, enable, enable);
  7488. };
  7489. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7490. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7491. if (this._alphaMode === mode) {
  7492. return;
  7493. }
  7494. switch (mode) {
  7495. case Engine.ALPHA_DISABLE:
  7496. this._alphaState.alphaBlend = false;
  7497. break;
  7498. case Engine.ALPHA_COMBINE:
  7499. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7500. this._alphaState.alphaBlend = true;
  7501. break;
  7502. case Engine.ALPHA_ONEONE:
  7503. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7504. this._alphaState.alphaBlend = true;
  7505. break;
  7506. case Engine.ALPHA_ADD:
  7507. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7508. this._alphaState.alphaBlend = true;
  7509. break;
  7510. case Engine.ALPHA_SUBTRACT:
  7511. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7512. this._alphaState.alphaBlend = true;
  7513. break;
  7514. case Engine.ALPHA_MULTIPLY:
  7515. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7516. this._alphaState.alphaBlend = true;
  7517. break;
  7518. case Engine.ALPHA_MAXIMIZED:
  7519. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7520. this._alphaState.alphaBlend = true;
  7521. break;
  7522. }
  7523. if (!noDepthWriteChange) {
  7524. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7525. }
  7526. this._alphaMode = mode;
  7527. };
  7528. Engine.prototype.getAlphaMode = function () {
  7529. return this._alphaMode;
  7530. };
  7531. Engine.prototype.setAlphaTesting = function (enable) {
  7532. this._alphaTest = enable;
  7533. };
  7534. Engine.prototype.getAlphaTesting = function () {
  7535. return this._alphaTest;
  7536. };
  7537. // Textures
  7538. Engine.prototype.wipeCaches = function () {
  7539. this.resetTextureCache();
  7540. this._currentEffect = null;
  7541. this._stencilState.reset();
  7542. this._depthCullingState.reset();
  7543. this.setDepthFunctionToLessOrEqual();
  7544. this._alphaState.reset();
  7545. this._cachedVertexBuffers = null;
  7546. this._cachedIndexBuffer = null;
  7547. this._cachedEffectForVertexBuffers = null;
  7548. };
  7549. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7550. var gl = this._gl;
  7551. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7552. var magFilter = gl.NEAREST;
  7553. var minFilter = gl.NEAREST;
  7554. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7555. magFilter = gl.LINEAR;
  7556. minFilter = gl.LINEAR;
  7557. }
  7558. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7559. magFilter = gl.LINEAR;
  7560. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7561. }
  7562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7564. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7565. texture.samplingMode = samplingMode;
  7566. };
  7567. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7568. var _this = this;
  7569. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7570. if (onLoad === void 0) { onLoad = null; }
  7571. if (onError === void 0) { onError = null; }
  7572. if (buffer === void 0) { buffer = null; }
  7573. var texture = this._gl.createTexture();
  7574. var extension;
  7575. var fromData = false;
  7576. if (url.substr(0, 5) === "data:") {
  7577. fromData = true;
  7578. }
  7579. if (!fromData)
  7580. extension = url.substr(url.length - 4, 4).toLowerCase();
  7581. else {
  7582. var oldUrl = url;
  7583. fromData = oldUrl.split(':');
  7584. url = oldUrl;
  7585. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7586. }
  7587. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7588. var isTGA = (extension === ".tga");
  7589. scene._addPendingData(texture);
  7590. texture.url = url;
  7591. texture.noMipmap = noMipmap;
  7592. texture.references = 1;
  7593. texture.samplingMode = samplingMode;
  7594. texture.onLoadedCallbacks = [onLoad];
  7595. this._loadedTexturesCache.push(texture);
  7596. var onerror = function () {
  7597. scene._removePendingData(texture);
  7598. if (onError) {
  7599. onError();
  7600. }
  7601. };
  7602. var callback;
  7603. if (isTGA) {
  7604. callback = function (arrayBuffer) {
  7605. var data = new Uint8Array(arrayBuffer);
  7606. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7607. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7608. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7609. }, samplingMode);
  7610. };
  7611. if (!(fromData instanceof Array))
  7612. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7613. callback(arrayBuffer);
  7614. }, null, scene.database, true, onerror);
  7615. else
  7616. callback(buffer);
  7617. }
  7618. else if (isDDS) {
  7619. callback = function (data) {
  7620. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7621. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7622. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7623. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7624. }, samplingMode);
  7625. };
  7626. if (!(fromData instanceof Array))
  7627. BABYLON.Tools.LoadFile(url, function (data) {
  7628. callback(data);
  7629. }, null, scene.database, true, onerror);
  7630. else
  7631. callback(buffer);
  7632. }
  7633. else {
  7634. var onload = function (img) {
  7635. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7636. var isPot = (img.width === potWidth && img.height === potHeight);
  7637. if (!isPot) {
  7638. _this._prepareWorkingCanvas();
  7639. _this._workingCanvas.width = potWidth;
  7640. _this._workingCanvas.height = potHeight;
  7641. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7642. _this._workingContext.imageSmoothingEnabled = false;
  7643. _this._workingContext.mozImageSmoothingEnabled = false;
  7644. _this._workingContext.oImageSmoothingEnabled = false;
  7645. _this._workingContext.webkitImageSmoothingEnabled = false;
  7646. _this._workingContext.msImageSmoothingEnabled = false;
  7647. }
  7648. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7649. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7650. _this._workingContext.imageSmoothingEnabled = true;
  7651. _this._workingContext.mozImageSmoothingEnabled = true;
  7652. _this._workingContext.oImageSmoothingEnabled = true;
  7653. _this._workingContext.webkitImageSmoothingEnabled = true;
  7654. _this._workingContext.msImageSmoothingEnabled = true;
  7655. }
  7656. }
  7657. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7658. }, samplingMode);
  7659. };
  7660. if (!(fromData instanceof Array))
  7661. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7662. else
  7663. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7664. }
  7665. return texture;
  7666. };
  7667. Engine.prototype._getInternalFormat = function (format) {
  7668. var internalFormat = this._gl.RGBA;
  7669. switch (format) {
  7670. case Engine.TEXTUREFORMAT_ALPHA:
  7671. internalFormat = this._gl.ALPHA;
  7672. break;
  7673. case Engine.TEXTUREFORMAT_LUMINANCE:
  7674. internalFormat = this._gl.LUMINANCE;
  7675. break;
  7676. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7677. internalFormat = this._gl.LUMINANCE_ALPHA;
  7678. break;
  7679. case Engine.TEXTUREFORMAT_RGB:
  7680. internalFormat = this._gl.RGB;
  7681. break;
  7682. case Engine.TEXTUREFORMAT_RGBA:
  7683. internalFormat = this._gl.RGBA;
  7684. break;
  7685. }
  7686. return internalFormat;
  7687. };
  7688. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7689. if (compression === void 0) { compression = null; }
  7690. var internalFormat = this._getInternalFormat(format);
  7691. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7692. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7693. if (texture._width % 4 !== 0) {
  7694. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7695. }
  7696. if (compression) {
  7697. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7698. }
  7699. else {
  7700. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7701. }
  7702. if (texture.generateMipMaps) {
  7703. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7704. }
  7705. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7706. this.resetTextureCache();
  7707. texture.isReady = true;
  7708. };
  7709. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  7710. if (compression === void 0) { compression = null; }
  7711. var texture = this._gl.createTexture();
  7712. texture._baseWidth = width;
  7713. texture._baseHeight = height;
  7714. texture._width = width;
  7715. texture._height = height;
  7716. texture.references = 1;
  7717. this.updateRawTexture(texture, data, format, invertY, compression);
  7718. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7719. // Filters
  7720. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  7721. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7722. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7723. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7724. texture.samplingMode = samplingMode;
  7725. this._loadedTexturesCache.push(texture);
  7726. return texture;
  7727. };
  7728. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  7729. var texture = this._gl.createTexture();
  7730. texture._baseWidth = width;
  7731. texture._baseHeight = height;
  7732. if (generateMipMaps) {
  7733. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  7734. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  7735. }
  7736. this.resetTextureCache();
  7737. texture._width = width;
  7738. texture._height = height;
  7739. texture.isReady = false;
  7740. texture.generateMipMaps = generateMipMaps;
  7741. texture.references = 1;
  7742. texture.samplingMode = samplingMode;
  7743. this.updateTextureSamplingMode(samplingMode, texture);
  7744. this._loadedTexturesCache.push(texture);
  7745. return texture;
  7746. };
  7747. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  7748. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  7749. if (texture.isCube) {
  7750. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  7751. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7752. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7753. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  7754. }
  7755. else {
  7756. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7757. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  7758. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  7759. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7760. }
  7761. };
  7762. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  7763. if (premulAlpha === void 0) { premulAlpha = false; }
  7764. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7765. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  7766. if (premulAlpha) {
  7767. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  7768. }
  7769. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  7770. if (texture.generateMipMaps) {
  7771. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7772. }
  7773. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7774. this.resetTextureCache();
  7775. texture.isReady = true;
  7776. };
  7777. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  7778. if (texture._isDisabled) {
  7779. return;
  7780. }
  7781. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7782. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  7783. try {
  7784. // Testing video texture support
  7785. if (this._videoTextureSupported === undefined) {
  7786. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7787. if (this._gl.getError() !== 0) {
  7788. this._videoTextureSupported = false;
  7789. }
  7790. else {
  7791. this._videoTextureSupported = true;
  7792. }
  7793. }
  7794. // Copy video through the current working canvas if video texture is not supported
  7795. if (!this._videoTextureSupported) {
  7796. if (!texture._workingCanvas) {
  7797. texture._workingCanvas = document.createElement("canvas");
  7798. texture._workingContext = texture._workingCanvas.getContext("2d");
  7799. texture._workingCanvas.width = texture._width;
  7800. texture._workingCanvas.height = texture._height;
  7801. }
  7802. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  7803. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  7804. }
  7805. else {
  7806. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  7807. }
  7808. if (texture.generateMipMaps) {
  7809. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7810. }
  7811. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  7812. this.resetTextureCache();
  7813. texture.isReady = true;
  7814. }
  7815. catch (ex) {
  7816. // Something unexpected
  7817. // Let's disable the texture
  7818. texture._isDisabled = true;
  7819. }
  7820. };
  7821. Engine.prototype.createRenderTargetTexture = function (size, options) {
  7822. // old version had a "generateMipMaps" arg instead of options.
  7823. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  7824. // in the same way, generateDepthBuffer is defaulted to true
  7825. var generateMipMaps = false;
  7826. var generateDepthBuffer = true;
  7827. var generateStencilBuffer = false;
  7828. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7829. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7830. if (options !== undefined) {
  7831. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7832. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7833. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7834. type = options.type === undefined ? type : options.type;
  7835. if (options.samplingMode !== undefined) {
  7836. samplingMode = options.samplingMode;
  7837. }
  7838. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  7839. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  7840. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7841. }
  7842. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  7843. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  7844. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  7845. }
  7846. }
  7847. var gl = this._gl;
  7848. var texture = gl.createTexture();
  7849. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7850. var width = size.width || size;
  7851. var height = size.height || size;
  7852. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7853. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  7854. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  7855. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  7856. }
  7857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  7858. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  7859. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7860. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7861. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  7862. var depthStencilBuffer;
  7863. // Create the depth/stencil buffer
  7864. if (generateStencilBuffer) {
  7865. depthStencilBuffer = gl.createRenderbuffer();
  7866. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7867. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  7868. }
  7869. else if (generateDepthBuffer) {
  7870. depthStencilBuffer = gl.createRenderbuffer();
  7871. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7872. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  7873. }
  7874. // Create the framebuffer
  7875. var framebuffer = gl.createFramebuffer();
  7876. this.bindUnboundFramebuffer(framebuffer);
  7877. // Manage attachments
  7878. if (generateStencilBuffer) {
  7879. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7880. }
  7881. else if (generateDepthBuffer) {
  7882. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7883. }
  7884. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  7885. if (generateMipMaps) {
  7886. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7887. }
  7888. // Unbind
  7889. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7890. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7891. this.bindUnboundFramebuffer(null);
  7892. texture._framebuffer = framebuffer;
  7893. if (generateDepthBuffer) {
  7894. texture._depthBuffer = depthStencilBuffer;
  7895. }
  7896. texture._baseWidth = width;
  7897. texture._baseHeight = height;
  7898. texture._width = width;
  7899. texture._height = height;
  7900. texture.isReady = true;
  7901. texture.generateMipMaps = generateMipMaps;
  7902. texture.references = 1;
  7903. texture.samplingMode = samplingMode;
  7904. texture.type = type;
  7905. this.resetTextureCache();
  7906. this._loadedTexturesCache.push(texture);
  7907. return texture;
  7908. };
  7909. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  7910. var gl = this._gl;
  7911. var texture = gl.createTexture();
  7912. var generateMipMaps = true;
  7913. var generateDepthBuffer = true;
  7914. var generateStencilBuffer = false;
  7915. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  7916. if (options !== undefined) {
  7917. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  7918. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  7919. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  7920. if (options.samplingMode !== undefined) {
  7921. samplingMode = options.samplingMode;
  7922. }
  7923. }
  7924. texture.isCube = true;
  7925. texture.references = 1;
  7926. texture.generateMipMaps = generateMipMaps;
  7927. texture.references = 1;
  7928. texture.samplingMode = samplingMode;
  7929. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  7930. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7931. for (var face = 0; face < 6; face++) {
  7932. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  7933. }
  7934. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  7935. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  7936. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  7937. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  7938. // Create the depth buffer
  7939. var depthStencilBuffer;
  7940. // Create the depth/stencil buffer
  7941. if (generateStencilBuffer) {
  7942. depthStencilBuffer = gl.createRenderbuffer();
  7943. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7944. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  7945. }
  7946. else if (generateDepthBuffer) {
  7947. depthStencilBuffer = gl.createRenderbuffer();
  7948. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  7949. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  7950. }
  7951. // Create the framebuffer
  7952. var framebuffer = gl.createFramebuffer();
  7953. this.bindUnboundFramebuffer(framebuffer);
  7954. // Manage attachments
  7955. if (generateStencilBuffer) {
  7956. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7957. }
  7958. else if (generateDepthBuffer) {
  7959. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  7960. }
  7961. // Mipmaps
  7962. if (texture.generateMipMaps) {
  7963. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7964. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7965. }
  7966. // Unbind
  7967. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7968. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  7969. this.bindUnboundFramebuffer(null);
  7970. texture._framebuffer = framebuffer;
  7971. if (generateDepthBuffer) {
  7972. texture._depthBuffer = depthStencilBuffer;
  7973. }
  7974. texture._width = size;
  7975. texture._height = size;
  7976. texture.isReady = true;
  7977. this.resetTextureCache();
  7978. this._loadedTexturesCache.push(texture);
  7979. return texture;
  7980. };
  7981. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap) {
  7982. var _this = this;
  7983. var gl = this._gl;
  7984. var texture = gl.createTexture();
  7985. texture.isCube = true;
  7986. texture.url = rootUrl;
  7987. texture.references = 1;
  7988. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  7989. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7990. if (isDDS) {
  7991. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  7992. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7993. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  7994. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7995. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  7996. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  7997. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  7998. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7999. }
  8000. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8001. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8002. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8003. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8004. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8005. _this.resetTextureCache();
  8006. texture._width = info.width;
  8007. texture._height = info.height;
  8008. texture.isReady = true;
  8009. }, null, null, true);
  8010. }
  8011. else {
  8012. cascadeLoad(rootUrl, scene, function (imgs) {
  8013. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8014. var height = width;
  8015. _this._prepareWorkingCanvas();
  8016. _this._workingCanvas.width = width;
  8017. _this._workingCanvas.height = height;
  8018. var faces = [
  8019. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8020. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8021. ];
  8022. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8023. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8024. for (var index = 0; index < faces.length; index++) {
  8025. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8026. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8027. }
  8028. if (!noMipmap) {
  8029. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8030. }
  8031. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8032. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8033. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8034. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8035. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8036. _this.resetTextureCache();
  8037. texture._width = width;
  8038. texture._height = height;
  8039. texture.isReady = true;
  8040. }, files);
  8041. }
  8042. this._loadedTexturesCache.push(texture);
  8043. return texture;
  8044. };
  8045. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8046. texture._width = width;
  8047. texture._height = height;
  8048. texture._size = width * height;
  8049. texture._baseWidth = width;
  8050. texture._baseHeight = height;
  8051. };
  8052. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8053. var _this = this;
  8054. var gl = this._gl;
  8055. var texture = gl.createTexture();
  8056. scene._addPendingData(texture);
  8057. texture.isCube = true;
  8058. texture.references = 1;
  8059. texture.url = url;
  8060. var internalFormat = this._getInternalFormat(format);
  8061. var textureType = gl.UNSIGNED_BYTE;
  8062. if (type === Engine.TEXTURETYPE_FLOAT) {
  8063. textureType = gl.FLOAT;
  8064. }
  8065. var width = size;
  8066. var height = width;
  8067. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8068. texture._width = width;
  8069. texture._height = height;
  8070. var onerror = function () {
  8071. scene._removePendingData(texture);
  8072. };
  8073. var internalCallback = function (data) {
  8074. var rgbeDataArrays = callback(data);
  8075. var facesIndex = [
  8076. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8077. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8078. ];
  8079. width = texture._width;
  8080. height = texture._height;
  8081. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8082. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8083. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8084. if (!noMipmap && isPot) {
  8085. if (mipmmapGenerator) {
  8086. var arrayTemp = [];
  8087. // Data are known to be in +X +Y +Z -X -Y -Z
  8088. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8089. arrayTemp.push(rgbeDataArrays[0]); // +X
  8090. arrayTemp.push(rgbeDataArrays[3]); // -X
  8091. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8092. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8093. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8094. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8095. var mipData = mipmmapGenerator(arrayTemp);
  8096. for (var level = 0; level < mipData.length; level++) {
  8097. var mipSize = width >> level;
  8098. // mipData is order in +X -X +Y -Y +Z -Z
  8099. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8100. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8101. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8102. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8103. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8104. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8105. }
  8106. }
  8107. else {
  8108. // Data are known to be in +X +Y +Z -X -Y -Z
  8109. for (var index = 0; index < facesIndex.length; index++) {
  8110. var faceData = rgbeDataArrays[index];
  8111. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8112. }
  8113. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8114. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8115. // By following the webgl standard changes from Revision 7, 2014/11/24
  8116. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8117. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8118. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8119. // Data are known to be in +X +Y +Z -X -Y -Z
  8120. for (var index = 0; index < facesIndex.length; index++) {
  8121. var faceData = rgbeDataArrays[index];
  8122. // Create a new RGBA Face.
  8123. var newFaceData = new Float32Array(width * height * 4);
  8124. for (var x = 0; x < width; x++) {
  8125. for (var y = 0; y < height; y++) {
  8126. var index_1 = (y * width + x) * 3;
  8127. var newIndex = (y * width + x) * 4;
  8128. // Map Old Value to new value.
  8129. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8130. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8131. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8132. // Add fully opaque alpha channel.
  8133. newFaceData[newIndex + 3] = 1;
  8134. }
  8135. }
  8136. // Reupload the face.
  8137. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8138. }
  8139. // Try to generate mipmap again.
  8140. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8141. }
  8142. }
  8143. }
  8144. else {
  8145. noMipmap = true;
  8146. }
  8147. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8148. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8149. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8150. }
  8151. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8152. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8153. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8154. }
  8155. else {
  8156. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8157. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8158. }
  8159. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8160. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8161. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8162. texture.isReady = true;
  8163. _this.resetTextureCache();
  8164. scene._removePendingData(texture);
  8165. };
  8166. BABYLON.Tools.LoadFile(url, function (data) {
  8167. internalCallback(data);
  8168. }, onerror, scene.database, true);
  8169. return texture;
  8170. };
  8171. ;
  8172. Engine.prototype._releaseTexture = function (texture) {
  8173. var gl = this._gl;
  8174. if (texture._framebuffer) {
  8175. gl.deleteFramebuffer(texture._framebuffer);
  8176. }
  8177. if (texture._depthBuffer) {
  8178. gl.deleteRenderbuffer(texture._depthBuffer);
  8179. }
  8180. gl.deleteTexture(texture);
  8181. // Unbind channels
  8182. this.unbindAllTextures();
  8183. var index = this._loadedTexturesCache.indexOf(texture);
  8184. if (index !== -1) {
  8185. this._loadedTexturesCache.splice(index, 1);
  8186. }
  8187. };
  8188. Engine.prototype.setProgram = function (program) {
  8189. if (this._currentProgram !== program) {
  8190. this._gl.useProgram(program);
  8191. this._currentProgram = program;
  8192. }
  8193. };
  8194. Engine.prototype.bindSamplers = function (effect) {
  8195. this.setProgram(effect.getProgram());
  8196. var samplers = effect.getSamplers();
  8197. for (var index = 0; index < samplers.length; index++) {
  8198. var uniform = effect.getUniform(samplers[index]);
  8199. this._gl.uniform1i(uniform, index);
  8200. }
  8201. this._currentEffect = null;
  8202. };
  8203. Engine.prototype.activateTexture = function (texture) {
  8204. if (this._activeTexture !== texture) {
  8205. this._gl.activeTexture(texture);
  8206. this._activeTexture = texture;
  8207. }
  8208. };
  8209. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8210. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8211. this._gl.bindTexture(target, texture);
  8212. this._activeTexturesCache[this._activeTexture] = texture;
  8213. }
  8214. };
  8215. Engine.prototype._bindTexture = function (channel, texture) {
  8216. if (channel < 0) {
  8217. return;
  8218. }
  8219. this.activateTexture(this._gl["TEXTURE" + channel]);
  8220. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8221. };
  8222. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8223. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8224. };
  8225. Engine.prototype.unbindAllTextures = function () {
  8226. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8227. this.activateTexture(this._gl["TEXTURE" + channel]);
  8228. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8229. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8230. }
  8231. };
  8232. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8233. if (channel < 0) {
  8234. return;
  8235. }
  8236. this._gl.uniform1i(uniform, channel);
  8237. this._setTexture(channel, texture);
  8238. };
  8239. Engine.prototype._setTexture = function (channel, texture) {
  8240. // Not ready?
  8241. if (!texture || !texture.isReady()) {
  8242. if (this._activeTexturesCache[channel] != null) {
  8243. this.activateTexture(this._gl["TEXTURE" + channel]);
  8244. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8245. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8246. }
  8247. return;
  8248. }
  8249. // Video
  8250. var alreadyActivated = false;
  8251. if (texture instanceof BABYLON.VideoTexture) {
  8252. this.activateTexture(this._gl["TEXTURE" + channel]);
  8253. alreadyActivated = true;
  8254. texture.update();
  8255. }
  8256. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8257. texture.delayLoad();
  8258. return;
  8259. }
  8260. var internalTexture = texture.getInternalTexture();
  8261. if (this._activeTexturesCache[channel] === internalTexture) {
  8262. return;
  8263. }
  8264. if (!alreadyActivated) {
  8265. this.activateTexture(this._gl["TEXTURE" + channel]);
  8266. }
  8267. if (internalTexture.isCube) {
  8268. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8269. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8270. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8271. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8272. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8273. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8274. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8275. }
  8276. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8277. }
  8278. else {
  8279. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8280. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8281. internalTexture._cachedWrapU = texture.wrapU;
  8282. switch (texture.wrapU) {
  8283. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8284. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8285. break;
  8286. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8287. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8288. break;
  8289. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8290. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8291. break;
  8292. }
  8293. }
  8294. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8295. internalTexture._cachedWrapV = texture.wrapV;
  8296. switch (texture.wrapV) {
  8297. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8298. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8299. break;
  8300. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8301. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8302. break;
  8303. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8304. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8305. break;
  8306. }
  8307. }
  8308. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8309. }
  8310. };
  8311. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8312. if (channel < 0) {
  8313. return;
  8314. }
  8315. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8316. this._textureUnits = new Int32Array(textures.length);
  8317. }
  8318. for (var i = 0; i < textures.length; i++) {
  8319. this._textureUnits[i] = channel + i;
  8320. }
  8321. this._gl.uniform1iv(uniform, this._textureUnits);
  8322. for (var index = 0; index < textures.length; index++) {
  8323. this._setTexture(channel + index, textures[index]);
  8324. }
  8325. };
  8326. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8327. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8328. var value = texture.anisotropicFilteringLevel;
  8329. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8330. value = 1;
  8331. }
  8332. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8333. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8334. texture._cachedAnisotropicFilteringLevel = value;
  8335. }
  8336. };
  8337. Engine.prototype.readPixels = function (x, y, width, height) {
  8338. var data = new Uint8Array(height * width * 4);
  8339. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8340. return data;
  8341. };
  8342. /**
  8343. * Add an externaly attached data from its key.
  8344. * This method call will fail and return false, if such key already exists.
  8345. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8346. * @param key the unique key that identifies the data
  8347. * @param data the data object to associate to the key for this Engine instance
  8348. * @return true if no such key were already present and the data was added successfully, false otherwise
  8349. */
  8350. Engine.prototype.addExternalData = function (key, data) {
  8351. return this._externalData.add(key, data);
  8352. };
  8353. /**
  8354. * Get an externaly attached data from its key
  8355. * @param key the unique key that identifies the data
  8356. * @return the associated data, if present (can be null), or undefined if not present
  8357. */
  8358. Engine.prototype.getExternalData = function (key) {
  8359. return this._externalData.get(key);
  8360. };
  8361. /**
  8362. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8363. * @param key the unique key that identifies the data
  8364. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8365. * @return the associated data, can be null if the factory returned null.
  8366. */
  8367. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8368. return this._externalData.getOrAddWithFactory(key, factory);
  8369. };
  8370. /**
  8371. * Remove an externaly attached data from the Engine instance
  8372. * @param key the unique key that identifies the data
  8373. * @return true if the data was successfully removed, false if it doesn't exist
  8374. */
  8375. Engine.prototype.removeExternalData = function (key) {
  8376. return this._externalData.remove(key);
  8377. };
  8378. Engine.prototype.releaseInternalTexture = function (texture) {
  8379. if (!texture) {
  8380. return;
  8381. }
  8382. texture.references--;
  8383. // Final reference ?
  8384. if (texture.references === 0) {
  8385. var texturesCache = this.getLoadedTexturesCache();
  8386. var index = texturesCache.indexOf(texture);
  8387. if (index > -1) {
  8388. texturesCache.splice(index, 1);
  8389. }
  8390. this._releaseTexture(texture);
  8391. }
  8392. };
  8393. // Dispose
  8394. Engine.prototype.dispose = function () {
  8395. this.hideLoadingUI();
  8396. this.stopRenderLoop();
  8397. // Release scenes
  8398. while (this.scenes.length) {
  8399. this.scenes[0].dispose();
  8400. }
  8401. // Release audio engine
  8402. Engine.audioEngine.dispose();
  8403. // Release effects
  8404. for (var name in this._compiledEffects) {
  8405. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8406. }
  8407. // Unbind
  8408. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8409. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8410. continue;
  8411. }
  8412. this._gl.disableVertexAttribArray(i);
  8413. }
  8414. this._gl = null;
  8415. //WebVR
  8416. this.disableVR();
  8417. // Events
  8418. window.removeEventListener("blur", this._onBlur);
  8419. window.removeEventListener("focus", this._onFocus);
  8420. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8421. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8422. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8423. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8424. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8425. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8426. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8427. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8428. };
  8429. // Loading screen
  8430. Engine.prototype.displayLoadingUI = function () {
  8431. this._loadingScreen.displayLoadingUI();
  8432. };
  8433. Engine.prototype.hideLoadingUI = function () {
  8434. this._loadingScreen.hideLoadingUI();
  8435. };
  8436. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8437. get: function () {
  8438. return this._loadingScreen;
  8439. },
  8440. set: function (loadingScreen) {
  8441. this._loadingScreen = loadingScreen;
  8442. },
  8443. enumerable: true,
  8444. configurable: true
  8445. });
  8446. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8447. set: function (text) {
  8448. this._loadingScreen.loadingUIText = text;
  8449. },
  8450. enumerable: true,
  8451. configurable: true
  8452. });
  8453. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8454. set: function (color) {
  8455. this._loadingScreen.loadingUIBackgroundColor = color;
  8456. },
  8457. enumerable: true,
  8458. configurable: true
  8459. });
  8460. Engine.prototype.attachContextLostEvent = function (callback) {
  8461. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8462. };
  8463. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8464. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8465. };
  8466. // FPS
  8467. Engine.prototype.getFps = function () {
  8468. return this.fps;
  8469. };
  8470. Engine.prototype.getDeltaTime = function () {
  8471. return this.deltaTime;
  8472. };
  8473. Engine.prototype._measureFps = function () {
  8474. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8475. var length = this.previousFramesDuration.length;
  8476. if (length >= 2) {
  8477. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8478. }
  8479. if (length >= this.fpsRange) {
  8480. if (length > this.fpsRange) {
  8481. this.previousFramesDuration.splice(0, 1);
  8482. length = this.previousFramesDuration.length;
  8483. }
  8484. var sum = 0;
  8485. for (var id = 0; id < length - 1; id++) {
  8486. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8487. }
  8488. this.fps = 1000.0 / (sum / (length - 1));
  8489. }
  8490. };
  8491. Engine.prototype._canRenderToFloatTexture = function () {
  8492. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8493. };
  8494. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8495. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8496. };
  8497. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8498. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8499. var tempcanvas = document.createElement("canvas");
  8500. tempcanvas.height = 16;
  8501. tempcanvas.width = 16;
  8502. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8503. // extension.
  8504. var ext = gl.getExtension(extension);
  8505. if (!ext) {
  8506. return false;
  8507. }
  8508. // setup GLSL program
  8509. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8510. var fragmentCode = "precision mediump float;\n uniform vec4 u_color;\n uniform sampler2D u_texture;\n\n void main() {\n gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n }";
  8511. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8512. gl.useProgram(program);
  8513. // look up where the vertex data needs to go.
  8514. var positionLocation = gl.getAttribLocation(program, "a_position");
  8515. var colorLoc = gl.getUniformLocation(program, "u_color");
  8516. // provide texture coordinates for the rectangle.
  8517. var positionBuffer = gl.createBuffer();
  8518. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8519. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8520. -1.0, -1.0,
  8521. 1.0, -1.0,
  8522. -1.0, 1.0,
  8523. -1.0, 1.0,
  8524. 1.0, -1.0,
  8525. 1.0, 1.0]), gl.STATIC_DRAW);
  8526. gl.enableVertexAttribArray(positionLocation);
  8527. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8528. var whiteTex = gl.createTexture();
  8529. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8530. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8531. var tex = gl.createTexture();
  8532. gl.bindTexture(gl.TEXTURE_2D, tex);
  8533. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8534. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8535. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8536. var fb = gl.createFramebuffer();
  8537. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8538. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8539. var cleanup = function () {
  8540. gl.deleteProgram(program);
  8541. gl.disableVertexAttribArray(positionLocation);
  8542. gl.deleteBuffer(positionBuffer);
  8543. gl.deleteFramebuffer(fb);
  8544. gl.deleteTexture(whiteTex);
  8545. gl.deleteTexture(tex);
  8546. };
  8547. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8548. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8549. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8550. cleanup();
  8551. return false;
  8552. }
  8553. // Draw the rectangle.
  8554. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8555. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8556. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8557. gl.bindTexture(gl.TEXTURE_2D, tex);
  8558. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8559. gl.clearColor(1, 0, 0, 1);
  8560. gl.clear(gl.COLOR_BUFFER_BIT);
  8561. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8562. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8563. var pixel = new Uint8Array(4);
  8564. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8565. if (pixel[0] !== 0 ||
  8566. pixel[1] < 248 ||
  8567. pixel[2] < 248 ||
  8568. pixel[3] < 254) {
  8569. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8570. cleanup();
  8571. return false;
  8572. }
  8573. // Succesfully rendered to "format" texture.
  8574. cleanup();
  8575. return true;
  8576. };
  8577. // Statics
  8578. Engine.isSupported = function () {
  8579. try {
  8580. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8581. if (navigator.isCocoonJS) {
  8582. return true;
  8583. }
  8584. var tempcanvas = document.createElement("canvas");
  8585. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8586. return gl != null && !!window.WebGLRenderingContext;
  8587. }
  8588. catch (e) {
  8589. return false;
  8590. }
  8591. };
  8592. // Const statics
  8593. Engine._ALPHA_DISABLE = 0;
  8594. Engine._ALPHA_ADD = 1;
  8595. Engine._ALPHA_COMBINE = 2;
  8596. Engine._ALPHA_SUBTRACT = 3;
  8597. Engine._ALPHA_MULTIPLY = 4;
  8598. Engine._ALPHA_MAXIMIZED = 5;
  8599. Engine._ALPHA_ONEONE = 6;
  8600. Engine._DELAYLOADSTATE_NONE = 0;
  8601. Engine._DELAYLOADSTATE_LOADED = 1;
  8602. Engine._DELAYLOADSTATE_LOADING = 2;
  8603. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8604. Engine._TEXTUREFORMAT_ALPHA = 0;
  8605. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8606. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8607. Engine._TEXTUREFORMAT_RGB = 4;
  8608. Engine._TEXTUREFORMAT_RGBA = 5;
  8609. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8610. Engine._TEXTURETYPE_FLOAT = 1;
  8611. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8612. // Updatable statics so stick with vars here
  8613. Engine.CollisionsEpsilon = 0.001;
  8614. Engine.CodeRepository = "src/";
  8615. Engine.ShadersRepository = "src/Shaders/";
  8616. return Engine;
  8617. }());
  8618. BABYLON.Engine = Engine;
  8619. })(BABYLON || (BABYLON = {}));
  8620. var BABYLON;
  8621. (function (BABYLON) {
  8622. /**
  8623. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8624. */
  8625. var Node = (function () {
  8626. /**
  8627. * @constructor
  8628. * @param {string} name - the name and id to be given to this node
  8629. * @param {BABYLON.Scene} the scene this node will be added to
  8630. */
  8631. function Node(name, scene) {
  8632. this.state = "";
  8633. this.animations = new Array();
  8634. this._ranges = {};
  8635. this._childrenFlag = -1;
  8636. this._isEnabled = true;
  8637. this._isReady = true;
  8638. this._currentRenderId = -1;
  8639. this._parentRenderId = -1;
  8640. this.name = name;
  8641. this.id = name;
  8642. this._scene = scene;
  8643. this._initCache();
  8644. }
  8645. Object.defineProperty(Node.prototype, "parent", {
  8646. get: function () {
  8647. return this._parentNode;
  8648. },
  8649. set: function (parent) {
  8650. if (this._parentNode === parent) {
  8651. return;
  8652. }
  8653. if (this._parentNode) {
  8654. var index = this._parentNode._children.indexOf(this);
  8655. if (index !== -1) {
  8656. this._parentNode._children.splice(index, 1);
  8657. }
  8658. }
  8659. this._parentNode = parent;
  8660. if (this._parentNode) {
  8661. if (!this._parentNode._children) {
  8662. this._parentNode._children = new Array();
  8663. }
  8664. this._parentNode._children.push(this);
  8665. }
  8666. },
  8667. enumerable: true,
  8668. configurable: true
  8669. });
  8670. Node.prototype.getScene = function () {
  8671. return this._scene;
  8672. };
  8673. Node.prototype.getEngine = function () {
  8674. return this._scene.getEngine();
  8675. };
  8676. // override it in derived class
  8677. Node.prototype.getWorldMatrix = function () {
  8678. return BABYLON.Matrix.Identity();
  8679. };
  8680. // override it in derived class if you add new variables to the cache
  8681. // and call the parent class method
  8682. Node.prototype._initCache = function () {
  8683. this._cache = {};
  8684. this._cache.parent = undefined;
  8685. };
  8686. Node.prototype.updateCache = function (force) {
  8687. if (!force && this.isSynchronized())
  8688. return;
  8689. this._cache.parent = this.parent;
  8690. this._updateCache();
  8691. };
  8692. // override it in derived class if you add new variables to the cache
  8693. // and call the parent class method if !ignoreParentClass
  8694. Node.prototype._updateCache = function (ignoreParentClass) {
  8695. };
  8696. // override it in derived class if you add new variables to the cache
  8697. Node.prototype._isSynchronized = function () {
  8698. return true;
  8699. };
  8700. Node.prototype._markSyncedWithParent = function () {
  8701. this._parentRenderId = this.parent._currentRenderId;
  8702. };
  8703. Node.prototype.isSynchronizedWithParent = function () {
  8704. if (!this.parent) {
  8705. return true;
  8706. }
  8707. if (this._parentRenderId !== this.parent._currentRenderId) {
  8708. return false;
  8709. }
  8710. return this.parent.isSynchronized();
  8711. };
  8712. Node.prototype.isSynchronized = function (updateCache) {
  8713. var check = this.hasNewParent();
  8714. check = check || !this.isSynchronizedWithParent();
  8715. check = check || !this._isSynchronized();
  8716. if (updateCache)
  8717. this.updateCache(true);
  8718. return !check;
  8719. };
  8720. Node.prototype.hasNewParent = function (update) {
  8721. if (this._cache.parent === this.parent)
  8722. return false;
  8723. if (update)
  8724. this._cache.parent = this.parent;
  8725. return true;
  8726. };
  8727. /**
  8728. * Is this node ready to be used/rendered
  8729. * @return {boolean} is it ready
  8730. */
  8731. Node.prototype.isReady = function () {
  8732. return this._isReady;
  8733. };
  8734. /**
  8735. * Is this node enabled.
  8736. * If the node has a parent and is enabled, the parent will be inspected as well.
  8737. * @return {boolean} whether this node (and its parent) is enabled.
  8738. * @see setEnabled
  8739. */
  8740. Node.prototype.isEnabled = function () {
  8741. if (!this._isEnabled) {
  8742. return false;
  8743. }
  8744. if (this.parent) {
  8745. return this.parent.isEnabled();
  8746. }
  8747. return true;
  8748. };
  8749. /**
  8750. * Set the enabled state of this node.
  8751. * @param {boolean} value - the new enabled state
  8752. * @see isEnabled
  8753. */
  8754. Node.prototype.setEnabled = function (value) {
  8755. this._isEnabled = value;
  8756. };
  8757. /**
  8758. * Is this node a descendant of the given node.
  8759. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  8760. * @param {BABYLON.Node} ancestor - The parent node to inspect
  8761. * @see parent
  8762. */
  8763. Node.prototype.isDescendantOf = function (ancestor) {
  8764. if (this.parent) {
  8765. if (this.parent === ancestor) {
  8766. return true;
  8767. }
  8768. return this.parent.isDescendantOf(ancestor);
  8769. }
  8770. return false;
  8771. };
  8772. /**
  8773. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  8774. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  8775. * @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.
  8776. * @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.
  8777. */
  8778. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  8779. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  8780. if (!this._children) {
  8781. return;
  8782. }
  8783. for (var index = 0; index < this._children.length; index++) {
  8784. var item = this._children[index];
  8785. if (!predicate || predicate(item)) {
  8786. results.push(item);
  8787. }
  8788. if (!directDescendantsOnly) {
  8789. item._getDescendants(results, false, predicate);
  8790. }
  8791. }
  8792. };
  8793. /**
  8794. * Will return all nodes that have this node as ascendant.
  8795. * @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.
  8796. * @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.
  8797. * @return {BABYLON.Node[]} all children nodes of all types.
  8798. */
  8799. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  8800. var results = [];
  8801. this._getDescendants(results, directDescendantsOnly, predicate);
  8802. return results;
  8803. };
  8804. /**
  8805. * @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.
  8806. * @Deprecated, legacy support.
  8807. * use getDecendants instead.
  8808. */
  8809. Node.prototype.getChildren = function (predicate) {
  8810. return this.getDescendants(true, predicate);
  8811. };
  8812. /**
  8813. * Get all child-meshes of this node.
  8814. */
  8815. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  8816. var results = [];
  8817. this._getDescendants(results, directDecendantsOnly, function (node) {
  8818. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  8819. });
  8820. return results;
  8821. };
  8822. Node.prototype._setReady = function (state) {
  8823. if (state === this._isReady) {
  8824. return;
  8825. }
  8826. if (!state) {
  8827. this._isReady = false;
  8828. return;
  8829. }
  8830. this._isReady = true;
  8831. if (this.onReady) {
  8832. this.onReady(this);
  8833. }
  8834. };
  8835. Node.prototype.getAnimationByName = function (name) {
  8836. for (var i = 0; i < this.animations.length; i++) {
  8837. var animation = this.animations[i];
  8838. if (animation.name === name) {
  8839. return animation;
  8840. }
  8841. }
  8842. return null;
  8843. };
  8844. Node.prototype.createAnimationRange = function (name, from, to) {
  8845. // check name not already in use
  8846. if (!this._ranges[name]) {
  8847. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  8848. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8849. if (this.animations[i]) {
  8850. this.animations[i].createRange(name, from, to);
  8851. }
  8852. }
  8853. }
  8854. };
  8855. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  8856. if (deleteFrames === void 0) { deleteFrames = true; }
  8857. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  8858. if (this.animations[i]) {
  8859. this.animations[i].deleteRange(name, deleteFrames);
  8860. }
  8861. }
  8862. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  8863. };
  8864. Node.prototype.getAnimationRange = function (name) {
  8865. return this._ranges[name];
  8866. };
  8867. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  8868. var range = this.getAnimationRange(name);
  8869. if (!range) {
  8870. return null;
  8871. }
  8872. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  8873. };
  8874. Node.prototype.serializeAnimationRanges = function () {
  8875. var serializationRanges = [];
  8876. for (var name in this._ranges) {
  8877. var range = {};
  8878. range.name = name;
  8879. range.from = this._ranges[name].from;
  8880. range.to = this._ranges[name].to;
  8881. serializationRanges.push(range);
  8882. }
  8883. return serializationRanges;
  8884. };
  8885. Node.prototype.dispose = function () {
  8886. this.parent = null;
  8887. };
  8888. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  8889. if (parsedNode.ranges) {
  8890. for (var index = 0; index < parsedNode.ranges.length; index++) {
  8891. var data = parsedNode.ranges[index];
  8892. node.createAnimationRange(data.name, data.from, data.to);
  8893. }
  8894. }
  8895. };
  8896. __decorate([
  8897. BABYLON.serialize()
  8898. ], Node.prototype, "name", void 0);
  8899. __decorate([
  8900. BABYLON.serialize()
  8901. ], Node.prototype, "id", void 0);
  8902. __decorate([
  8903. BABYLON.serialize()
  8904. ], Node.prototype, "uniqueId", void 0);
  8905. __decorate([
  8906. BABYLON.serialize()
  8907. ], Node.prototype, "state", void 0);
  8908. return Node;
  8909. }());
  8910. BABYLON.Node = Node;
  8911. })(BABYLON || (BABYLON = {}));
  8912. var BABYLON;
  8913. (function (BABYLON) {
  8914. var FilesInput = (function () {
  8915. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  8916. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  8917. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  8918. this._engine = p_engine;
  8919. this._canvas = p_canvas;
  8920. this._currentScene = p_scene;
  8921. this._sceneLoadedCallback = p_sceneLoadedCallback;
  8922. this._progressCallback = p_progressCallback;
  8923. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  8924. this._textureLoadingCallback = p_textureLoadingCallback;
  8925. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  8926. }
  8927. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  8928. var _this = this;
  8929. if (p_elementToMonitor) {
  8930. this._elementToMonitor = p_elementToMonitor;
  8931. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  8932. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  8933. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  8934. }
  8935. };
  8936. FilesInput.prototype.renderFunction = function () {
  8937. if (this._additionnalRenderLoopLogicCallback) {
  8938. this._additionnalRenderLoopLogicCallback();
  8939. }
  8940. if (this._currentScene) {
  8941. if (this._textureLoadingCallback) {
  8942. var remaining = this._currentScene.getWaitingItemsCount();
  8943. if (remaining > 0) {
  8944. this._textureLoadingCallback(remaining);
  8945. }
  8946. }
  8947. this._currentScene.render();
  8948. }
  8949. };
  8950. FilesInput.prototype.drag = function (e) {
  8951. e.stopPropagation();
  8952. e.preventDefault();
  8953. };
  8954. FilesInput.prototype.drop = function (eventDrop) {
  8955. eventDrop.stopPropagation();
  8956. eventDrop.preventDefault();
  8957. this.loadFiles(eventDrop);
  8958. };
  8959. FilesInput.prototype.loadFiles = function (event) {
  8960. if (this._startingProcessingFilesCallback)
  8961. this._startingProcessingFilesCallback();
  8962. // Handling data transfer via drag'n'drop
  8963. if (event && event.dataTransfer && event.dataTransfer.files) {
  8964. this._filesToLoad = event.dataTransfer.files;
  8965. }
  8966. // Handling files from input files
  8967. if (event && event.target && event.target.files) {
  8968. this._filesToLoad = event.target.files;
  8969. }
  8970. if (this._filesToLoad && this._filesToLoad.length > 0) {
  8971. for (var i = 0; i < this._filesToLoad.length; i++) {
  8972. switch (this._filesToLoad[i].type) {
  8973. case "image/jpeg":
  8974. case "image/png":
  8975. case "image/bmp":
  8976. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8977. break;
  8978. case "image/targa":
  8979. case "image/vnd.ms-dds":
  8980. case "audio/wav":
  8981. case "audio/x-wav":
  8982. case "audio/mp3":
  8983. case "audio/mpeg":
  8984. case "audio/mpeg3":
  8985. case "audio/x-mpeg-3":
  8986. case "audio/ogg":
  8987. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8988. break;
  8989. default:
  8990. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  8991. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  8992. }
  8993. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  8994. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  8995. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  8996. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  8997. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  8998. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  8999. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9000. this._sceneFileToLoad = this._filesToLoad[i];
  9001. }
  9002. break;
  9003. }
  9004. }
  9005. this.reload();
  9006. }
  9007. };
  9008. FilesInput.prototype.reload = function () {
  9009. var _this = this;
  9010. var that = this;
  9011. // If a ".babylon" file has been provided
  9012. if (this._sceneFileToLoad) {
  9013. if (this._currentScene) {
  9014. if (BABYLON.Tools.errorsCount > 0) {
  9015. BABYLON.Tools.ClearLogCache();
  9016. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9017. }
  9018. this._engine.stopRenderLoop();
  9019. this._currentScene.dispose();
  9020. }
  9021. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9022. that._currentScene = newScene;
  9023. // Wait for textures and shaders to be ready
  9024. that._currentScene.executeWhenReady(function () {
  9025. // Attach camera to canvas inputs
  9026. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9027. that._currentScene.createDefaultCameraOrLight();
  9028. }
  9029. that._currentScene.activeCamera.attachControl(that._canvas);
  9030. if (that._sceneLoadedCallback) {
  9031. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9032. }
  9033. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9034. });
  9035. }, function (progress) {
  9036. if (_this._progressCallback) {
  9037. _this._progressCallback(progress);
  9038. }
  9039. });
  9040. }
  9041. else {
  9042. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9043. }
  9044. };
  9045. FilesInput.FilesTextures = new Array();
  9046. FilesInput.FilesToLoad = new Array();
  9047. return FilesInput;
  9048. }());
  9049. BABYLON.FilesInput = FilesInput;
  9050. })(BABYLON || (BABYLON = {}));
  9051. var BABYLON;
  9052. (function (BABYLON) {
  9053. var IntersectionInfo = (function () {
  9054. function IntersectionInfo(bu, bv, distance) {
  9055. this.bu = bu;
  9056. this.bv = bv;
  9057. this.distance = distance;
  9058. this.faceId = 0;
  9059. this.subMeshId = 0;
  9060. }
  9061. return IntersectionInfo;
  9062. }());
  9063. BABYLON.IntersectionInfo = IntersectionInfo;
  9064. var PickingInfo = (function () {
  9065. function PickingInfo() {
  9066. this.hit = false;
  9067. this.distance = 0;
  9068. this.pickedPoint = null;
  9069. this.pickedMesh = null;
  9070. this.bu = 0;
  9071. this.bv = 0;
  9072. this.faceId = -1;
  9073. this.subMeshId = 0;
  9074. this.pickedSprite = null;
  9075. }
  9076. // Methods
  9077. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9078. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9079. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9080. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9081. return null;
  9082. }
  9083. var indices = this.pickedMesh.getIndices();
  9084. var result;
  9085. if (useVerticesNormals) {
  9086. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9087. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9088. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9089. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9090. normal0 = normal0.scale(this.bu);
  9091. normal1 = normal1.scale(this.bv);
  9092. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9093. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9094. }
  9095. else {
  9096. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9097. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9098. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9099. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9100. var p1p2 = vertex1.subtract(vertex2);
  9101. var p3p2 = vertex3.subtract(vertex2);
  9102. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9103. }
  9104. if (useWorldCoordinates) {
  9105. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9106. }
  9107. return BABYLON.Vector3.Normalize(result);
  9108. };
  9109. PickingInfo.prototype.getTextureCoordinates = function () {
  9110. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9111. return null;
  9112. }
  9113. var indices = this.pickedMesh.getIndices();
  9114. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9115. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9116. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9117. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9118. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9119. uv1 = uv1.scale(this.bu);
  9120. uv2 = uv2.scale(this.bv);
  9121. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9122. };
  9123. return PickingInfo;
  9124. }());
  9125. BABYLON.PickingInfo = PickingInfo;
  9126. })(BABYLON || (BABYLON = {}));
  9127. var BABYLON;
  9128. (function (BABYLON) {
  9129. var BoundingSphere = (function () {
  9130. function BoundingSphere(minimum, maximum) {
  9131. this.minimum = minimum;
  9132. this.maximum = maximum;
  9133. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9134. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9135. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9136. this.radius = distance * 0.5;
  9137. this.centerWorld = BABYLON.Vector3.Zero();
  9138. this._update(BABYLON.Matrix.Identity());
  9139. }
  9140. // Methods
  9141. BoundingSphere.prototype._update = function (world) {
  9142. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9143. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9144. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9145. };
  9146. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9147. for (var i = 0; i < 6; i++) {
  9148. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9149. return false;
  9150. }
  9151. return true;
  9152. };
  9153. BoundingSphere.prototype.intersectsPoint = function (point) {
  9154. var x = this.centerWorld.x - point.x;
  9155. var y = this.centerWorld.y - point.y;
  9156. var z = this.centerWorld.z - point.z;
  9157. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9158. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9159. return false;
  9160. return true;
  9161. };
  9162. // Statics
  9163. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9164. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9165. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9166. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9167. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9168. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9169. return false;
  9170. return true;
  9171. };
  9172. return BoundingSphere;
  9173. }());
  9174. BABYLON.BoundingSphere = BoundingSphere;
  9175. })(BABYLON || (BABYLON = {}));
  9176. var BABYLON;
  9177. (function (BABYLON) {
  9178. var BoundingBox = (function () {
  9179. function BoundingBox(minimum, maximum) {
  9180. this.minimum = minimum;
  9181. this.maximum = maximum;
  9182. this.vectors = new Array();
  9183. this.vectorsWorld = new Array();
  9184. // Bounding vectors
  9185. this.vectors.push(this.minimum.clone());
  9186. this.vectors.push(this.maximum.clone());
  9187. this.vectors.push(this.minimum.clone());
  9188. this.vectors[2].x = this.maximum.x;
  9189. this.vectors.push(this.minimum.clone());
  9190. this.vectors[3].y = this.maximum.y;
  9191. this.vectors.push(this.minimum.clone());
  9192. this.vectors[4].z = this.maximum.z;
  9193. this.vectors.push(this.maximum.clone());
  9194. this.vectors[5].z = this.minimum.z;
  9195. this.vectors.push(this.maximum.clone());
  9196. this.vectors[6].x = this.minimum.x;
  9197. this.vectors.push(this.maximum.clone());
  9198. this.vectors[7].y = this.minimum.y;
  9199. // OBB
  9200. this.center = this.maximum.add(this.minimum).scale(0.5);
  9201. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9202. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9203. // World
  9204. for (var index = 0; index < this.vectors.length; index++) {
  9205. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9206. }
  9207. this.minimumWorld = BABYLON.Vector3.Zero();
  9208. this.maximumWorld = BABYLON.Vector3.Zero();
  9209. this._update(BABYLON.Matrix.Identity());
  9210. }
  9211. // Methods
  9212. BoundingBox.prototype.getWorldMatrix = function () {
  9213. return this._worldMatrix;
  9214. };
  9215. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9216. this._worldMatrix.copyFrom(matrix);
  9217. return this;
  9218. };
  9219. BoundingBox.prototype._update = function (world) {
  9220. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9221. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9222. for (var index = 0; index < this.vectors.length; index++) {
  9223. var v = this.vectorsWorld[index];
  9224. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9225. if (v.x < this.minimumWorld.x)
  9226. this.minimumWorld.x = v.x;
  9227. if (v.y < this.minimumWorld.y)
  9228. this.minimumWorld.y = v.y;
  9229. if (v.z < this.minimumWorld.z)
  9230. this.minimumWorld.z = v.z;
  9231. if (v.x > this.maximumWorld.x)
  9232. this.maximumWorld.x = v.x;
  9233. if (v.y > this.maximumWorld.y)
  9234. this.maximumWorld.y = v.y;
  9235. if (v.z > this.maximumWorld.z)
  9236. this.maximumWorld.z = v.z;
  9237. }
  9238. // OBB
  9239. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9240. this.center.scaleInPlace(0.5);
  9241. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9242. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9243. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9244. this._worldMatrix = world;
  9245. };
  9246. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9247. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9248. };
  9249. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9250. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9251. };
  9252. BoundingBox.prototype.intersectsPoint = function (point) {
  9253. var delta = -BABYLON.Epsilon;
  9254. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9255. return false;
  9256. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9257. return false;
  9258. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9259. return false;
  9260. return true;
  9261. };
  9262. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9263. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9264. };
  9265. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9266. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9267. return false;
  9268. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9269. return false;
  9270. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9271. return false;
  9272. return true;
  9273. };
  9274. // Statics
  9275. BoundingBox.Intersects = function (box0, box1) {
  9276. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9277. return false;
  9278. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9279. return false;
  9280. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9281. return false;
  9282. return true;
  9283. };
  9284. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9285. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9286. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9287. return (num <= (sphereRadius * sphereRadius));
  9288. };
  9289. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9290. for (var p = 0; p < 6; p++) {
  9291. for (var i = 0; i < 8; i++) {
  9292. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9293. return false;
  9294. }
  9295. }
  9296. }
  9297. return true;
  9298. };
  9299. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9300. for (var p = 0; p < 6; p++) {
  9301. var inCount = 8;
  9302. for (var i = 0; i < 8; i++) {
  9303. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9304. --inCount;
  9305. }
  9306. else {
  9307. break;
  9308. }
  9309. }
  9310. if (inCount === 0)
  9311. return false;
  9312. }
  9313. return true;
  9314. };
  9315. return BoundingBox;
  9316. }());
  9317. BABYLON.BoundingBox = BoundingBox;
  9318. })(BABYLON || (BABYLON = {}));
  9319. var BABYLON;
  9320. (function (BABYLON) {
  9321. var computeBoxExtents = function (axis, box) {
  9322. var p = BABYLON.Vector3.Dot(box.center, axis);
  9323. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9324. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9325. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9326. var r = r0 + r1 + r2;
  9327. return {
  9328. min: p - r,
  9329. max: p + r
  9330. };
  9331. };
  9332. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9333. var axisOverlap = function (axis, box0, box1) {
  9334. var result0 = computeBoxExtents(axis, box0);
  9335. var result1 = computeBoxExtents(axis, box1);
  9336. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9337. };
  9338. var BoundingInfo = (function () {
  9339. function BoundingInfo(minimum, maximum) {
  9340. this.minimum = minimum;
  9341. this.maximum = maximum;
  9342. this._isLocked = false;
  9343. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9344. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9345. }
  9346. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9347. get: function () {
  9348. return this._isLocked;
  9349. },
  9350. set: function (value) {
  9351. this._isLocked = value;
  9352. },
  9353. enumerable: true,
  9354. configurable: true
  9355. });
  9356. // Methods
  9357. BoundingInfo.prototype.update = function (world) {
  9358. if (this._isLocked) {
  9359. return;
  9360. }
  9361. this.boundingBox._update(world);
  9362. this.boundingSphere._update(world);
  9363. };
  9364. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9365. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9366. return false;
  9367. return this.boundingBox.isInFrustum(frustumPlanes);
  9368. };
  9369. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9370. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9371. };
  9372. BoundingInfo.prototype._checkCollision = function (collider) {
  9373. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9374. };
  9375. BoundingInfo.prototype.intersectsPoint = function (point) {
  9376. if (!this.boundingSphere.centerWorld) {
  9377. return false;
  9378. }
  9379. if (!this.boundingSphere.intersectsPoint(point)) {
  9380. return false;
  9381. }
  9382. if (!this.boundingBox.intersectsPoint(point)) {
  9383. return false;
  9384. }
  9385. return true;
  9386. };
  9387. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9388. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9389. return false;
  9390. }
  9391. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9392. return false;
  9393. }
  9394. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9395. return false;
  9396. }
  9397. if (!precise) {
  9398. return true;
  9399. }
  9400. var box0 = this.boundingBox;
  9401. var box1 = boundingInfo.boundingBox;
  9402. if (!axisOverlap(box0.directions[0], box0, box1))
  9403. return false;
  9404. if (!axisOverlap(box0.directions[1], box0, box1))
  9405. return false;
  9406. if (!axisOverlap(box0.directions[2], box0, box1))
  9407. return false;
  9408. if (!axisOverlap(box1.directions[0], box0, box1))
  9409. return false;
  9410. if (!axisOverlap(box1.directions[1], box0, box1))
  9411. return false;
  9412. if (!axisOverlap(box1.directions[2], box0, box1))
  9413. return false;
  9414. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9415. return false;
  9416. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9417. return false;
  9418. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9419. return false;
  9420. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9421. return false;
  9422. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9423. return false;
  9424. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9425. return false;
  9426. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9427. return false;
  9428. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9429. return false;
  9430. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9431. return false;
  9432. return true;
  9433. };
  9434. return BoundingInfo;
  9435. }());
  9436. BABYLON.BoundingInfo = BoundingInfo;
  9437. })(BABYLON || (BABYLON = {}));
  9438. var BABYLON;
  9439. (function (BABYLON) {
  9440. var Ray = (function () {
  9441. function Ray(origin, direction, length) {
  9442. if (length === void 0) { length = Number.MAX_VALUE; }
  9443. this.origin = origin;
  9444. this.direction = direction;
  9445. this.length = length;
  9446. }
  9447. // Methods
  9448. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9449. var d = 0.0;
  9450. var maxValue = Number.MAX_VALUE;
  9451. var inv;
  9452. var min;
  9453. var max;
  9454. var temp;
  9455. if (Math.abs(this.direction.x) < 0.0000001) {
  9456. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9457. return false;
  9458. }
  9459. }
  9460. else {
  9461. inv = 1.0 / this.direction.x;
  9462. min = (minimum.x - this.origin.x) * inv;
  9463. max = (maximum.x - this.origin.x) * inv;
  9464. if (max === -Infinity) {
  9465. max = Infinity;
  9466. }
  9467. if (min > max) {
  9468. temp = min;
  9469. min = max;
  9470. max = temp;
  9471. }
  9472. d = Math.max(min, d);
  9473. maxValue = Math.min(max, maxValue);
  9474. if (d > maxValue) {
  9475. return false;
  9476. }
  9477. }
  9478. if (Math.abs(this.direction.y) < 0.0000001) {
  9479. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9480. return false;
  9481. }
  9482. }
  9483. else {
  9484. inv = 1.0 / this.direction.y;
  9485. min = (minimum.y - this.origin.y) * inv;
  9486. max = (maximum.y - this.origin.y) * inv;
  9487. if (max === -Infinity) {
  9488. max = Infinity;
  9489. }
  9490. if (min > max) {
  9491. temp = min;
  9492. min = max;
  9493. max = temp;
  9494. }
  9495. d = Math.max(min, d);
  9496. maxValue = Math.min(max, maxValue);
  9497. if (d > maxValue) {
  9498. return false;
  9499. }
  9500. }
  9501. if (Math.abs(this.direction.z) < 0.0000001) {
  9502. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9503. return false;
  9504. }
  9505. }
  9506. else {
  9507. inv = 1.0 / this.direction.z;
  9508. min = (minimum.z - this.origin.z) * inv;
  9509. max = (maximum.z - this.origin.z) * inv;
  9510. if (max === -Infinity) {
  9511. max = Infinity;
  9512. }
  9513. if (min > max) {
  9514. temp = min;
  9515. min = max;
  9516. max = temp;
  9517. }
  9518. d = Math.max(min, d);
  9519. maxValue = Math.min(max, maxValue);
  9520. if (d > maxValue) {
  9521. return false;
  9522. }
  9523. }
  9524. return true;
  9525. };
  9526. Ray.prototype.intersectsBox = function (box) {
  9527. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9528. };
  9529. Ray.prototype.intersectsSphere = function (sphere) {
  9530. var x = sphere.center.x - this.origin.x;
  9531. var y = sphere.center.y - this.origin.y;
  9532. var z = sphere.center.z - this.origin.z;
  9533. var pyth = (x * x) + (y * y) + (z * z);
  9534. var rr = sphere.radius * sphere.radius;
  9535. if (pyth <= rr) {
  9536. return true;
  9537. }
  9538. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9539. if (dot < 0.0) {
  9540. return false;
  9541. }
  9542. var temp = pyth - (dot * dot);
  9543. return temp <= rr;
  9544. };
  9545. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9546. if (!this._edge1) {
  9547. this._edge1 = BABYLON.Vector3.Zero();
  9548. this._edge2 = BABYLON.Vector3.Zero();
  9549. this._pvec = BABYLON.Vector3.Zero();
  9550. this._tvec = BABYLON.Vector3.Zero();
  9551. this._qvec = BABYLON.Vector3.Zero();
  9552. }
  9553. vertex1.subtractToRef(vertex0, this._edge1);
  9554. vertex2.subtractToRef(vertex0, this._edge2);
  9555. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9556. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9557. if (det === 0) {
  9558. return null;
  9559. }
  9560. var invdet = 1 / det;
  9561. this.origin.subtractToRef(vertex0, this._tvec);
  9562. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9563. if (bu < 0 || bu > 1.0) {
  9564. return null;
  9565. }
  9566. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9567. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9568. if (bv < 0 || bu + bv > 1.0) {
  9569. return null;
  9570. }
  9571. //check if the distance is longer than the predefined length.
  9572. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9573. if (distance > this.length) {
  9574. return null;
  9575. }
  9576. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9577. };
  9578. Ray.prototype.intersectsPlane = function (plane) {
  9579. var distance;
  9580. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9581. if (Math.abs(result1) < 9.99999997475243E-07) {
  9582. return null;
  9583. }
  9584. else {
  9585. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9586. distance = (-plane.d - result2) / result1;
  9587. if (distance < 0.0) {
  9588. if (distance < -9.99999997475243E-07) {
  9589. return null;
  9590. }
  9591. else {
  9592. return 0;
  9593. }
  9594. }
  9595. return distance;
  9596. }
  9597. };
  9598. /**
  9599. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9600. * @param sega the first point of the segment to test the intersection against
  9601. * @param segb the second point of the segment to test the intersection against
  9602. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9603. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9604. */
  9605. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9606. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9607. var u = segb.subtract(sega);
  9608. var v = rsegb.subtract(this.origin);
  9609. var w = sega.subtract(this.origin);
  9610. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9611. var b = BABYLON.Vector3.Dot(u, v);
  9612. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9613. var d = BABYLON.Vector3.Dot(u, w);
  9614. var e = BABYLON.Vector3.Dot(v, w);
  9615. var D = a * c - b * b; // always >= 0
  9616. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9617. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9618. // compute the line parameters of the two closest points
  9619. if (D < Ray.smallnum) {
  9620. sN = 0.0; // force using point P0 on segment S1
  9621. sD = 1.0; // to prevent possible division by 0.0 later
  9622. tN = e;
  9623. tD = c;
  9624. }
  9625. else {
  9626. sN = (b * e - c * d);
  9627. tN = (a * e - b * d);
  9628. if (sN < 0.0) {
  9629. sN = 0.0;
  9630. tN = e;
  9631. tD = c;
  9632. }
  9633. else if (sN > sD) {
  9634. sN = sD;
  9635. tN = e + b;
  9636. tD = c;
  9637. }
  9638. }
  9639. if (tN < 0.0) {
  9640. tN = 0.0;
  9641. // recompute sc for this edge
  9642. if (-d < 0.0) {
  9643. sN = 0.0;
  9644. }
  9645. else if (-d > a)
  9646. sN = sD;
  9647. else {
  9648. sN = -d;
  9649. sD = a;
  9650. }
  9651. }
  9652. else if (tN > tD) {
  9653. tN = tD;
  9654. // recompute sc for this edge
  9655. if ((-d + b) < 0.0) {
  9656. sN = 0;
  9657. }
  9658. else if ((-d + b) > a) {
  9659. sN = sD;
  9660. }
  9661. else {
  9662. sN = (-d + b);
  9663. sD = a;
  9664. }
  9665. }
  9666. // finally do the division to get sc and tc
  9667. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  9668. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  9669. // get the difference of the two closest points
  9670. var qtc = v.multiplyByFloats(tc, tc, tc);
  9671. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  9672. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  9673. if (isIntersected) {
  9674. return qtc.length();
  9675. }
  9676. return -1;
  9677. };
  9678. // Statics
  9679. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  9680. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  9681. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  9682. var direction = end.subtract(start);
  9683. direction.normalize();
  9684. return new Ray(start, direction);
  9685. };
  9686. /**
  9687. * 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
  9688. * transformed to the given world matrix.
  9689. * @param origin The origin point
  9690. * @param end The end point
  9691. * @param world a matrix to transform the ray to. Default is the identity matrix.
  9692. */
  9693. Ray.CreateNewFromTo = function (origin, end, world) {
  9694. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  9695. var direction = end.subtract(origin);
  9696. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  9697. direction.normalize();
  9698. return Ray.Transform(new Ray(origin, direction, length), world);
  9699. };
  9700. Ray.Transform = function (ray, matrix) {
  9701. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  9702. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  9703. newDirection.normalize();
  9704. return new Ray(newOrigin, newDirection, ray.length);
  9705. };
  9706. Ray.smallnum = 0.00000001;
  9707. Ray.rayl = 10e8;
  9708. return Ray;
  9709. }());
  9710. BABYLON.Ray = Ray;
  9711. })(BABYLON || (BABYLON = {}));
  9712. var BABYLON;
  9713. (function (BABYLON) {
  9714. var AbstractMesh = (function (_super) {
  9715. __extends(AbstractMesh, _super);
  9716. // Constructor
  9717. function AbstractMesh(name, scene) {
  9718. var _this = this;
  9719. _super.call(this, name, scene);
  9720. // Events
  9721. /**
  9722. * An event triggered when the mesh is disposed.
  9723. * @type {BABYLON.Observable}
  9724. */
  9725. this.onDisposeObservable = new BABYLON.Observable();
  9726. /**
  9727. * An event triggered when this mesh collides with another one
  9728. * @type {BABYLON.Observable}
  9729. */
  9730. this.onCollideObservable = new BABYLON.Observable();
  9731. /**
  9732. * An event triggered when the collision's position changes
  9733. * @type {BABYLON.Observable}
  9734. */
  9735. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  9736. /**
  9737. * An event triggered after the world matrix is updated
  9738. * @type {BABYLON.Observable}
  9739. */
  9740. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  9741. // Properties
  9742. this.definedFacingForward = true; // orientation for POV movement & rotation
  9743. this.position = new BABYLON.Vector3(0, 0, 0);
  9744. this._rotation = new BABYLON.Vector3(0, 0, 0);
  9745. this._scaling = new BABYLON.Vector3(1, 1, 1);
  9746. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9747. this.visibility = 1.0;
  9748. this.alphaIndex = Number.MAX_VALUE;
  9749. this.infiniteDistance = false;
  9750. this.isVisible = true;
  9751. this.isPickable = true;
  9752. this.showBoundingBox = false;
  9753. this.showSubMeshesBoundingBox = false;
  9754. this.isBlocker = false;
  9755. this.renderingGroupId = 0;
  9756. this.receiveShadows = false;
  9757. this.renderOutline = false;
  9758. this.outlineColor = BABYLON.Color3.Red();
  9759. this.outlineWidth = 0.02;
  9760. this.renderOverlay = false;
  9761. this.overlayColor = BABYLON.Color3.Red();
  9762. this.overlayAlpha = 0.5;
  9763. this.hasVertexAlpha = false;
  9764. this.useVertexColors = true;
  9765. this.applyFog = true;
  9766. this.computeBonesUsingShaders = true;
  9767. this.scalingDeterminant = 1;
  9768. this.numBoneInfluencers = 4;
  9769. this.useOctreeForRenderingSelection = true;
  9770. this.useOctreeForPicking = true;
  9771. this.useOctreeForCollisions = true;
  9772. this.layerMask = 0x0FFFFFFF;
  9773. this.alwaysSelectAsActiveMesh = false;
  9774. // Collisions
  9775. this._checkCollisions = false;
  9776. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9777. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9778. this._collider = new BABYLON.Collider();
  9779. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9780. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9781. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9782. // Edges
  9783. this.edgesWidth = 1;
  9784. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  9785. // Cache
  9786. this._localWorld = BABYLON.Matrix.Zero();
  9787. this._worldMatrix = BABYLON.Matrix.Zero();
  9788. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9789. this._absolutePosition = BABYLON.Vector3.Zero();
  9790. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9791. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9792. this._isDirty = false;
  9793. this._pivotMatrix = BABYLON.Matrix.Identity();
  9794. this._isDisposed = false;
  9795. this._renderId = 0;
  9796. this._intersectionsInProgress = new Array();
  9797. this._isWorldMatrixFrozen = false;
  9798. this._unIndexed = false;
  9799. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  9800. if (collidedMesh === void 0) { collidedMesh = null; }
  9801. //TODO move this to the collision coordinator!
  9802. if (_this.getScene().workerCollisions)
  9803. newPosition.multiplyInPlace(_this._collider.radius);
  9804. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  9805. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9806. _this.position.addInPlace(_this._diffPositionForCollisions);
  9807. }
  9808. if (collidedMesh) {
  9809. _this.onCollideObservable.notifyObservers(collidedMesh);
  9810. }
  9811. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  9812. };
  9813. scene.addMesh(this);
  9814. }
  9815. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9816. get: function () {
  9817. return AbstractMesh._BILLBOARDMODE_NONE;
  9818. },
  9819. enumerable: true,
  9820. configurable: true
  9821. });
  9822. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9823. get: function () {
  9824. return AbstractMesh._BILLBOARDMODE_X;
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9830. get: function () {
  9831. return AbstractMesh._BILLBOARDMODE_Y;
  9832. },
  9833. enumerable: true,
  9834. configurable: true
  9835. });
  9836. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9837. get: function () {
  9838. return AbstractMesh._BILLBOARDMODE_Z;
  9839. },
  9840. enumerable: true,
  9841. configurable: true
  9842. });
  9843. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9844. get: function () {
  9845. return AbstractMesh._BILLBOARDMODE_ALL;
  9846. },
  9847. enumerable: true,
  9848. configurable: true
  9849. });
  9850. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  9851. set: function (callback) {
  9852. if (this._onDisposeObserver) {
  9853. this.onDisposeObservable.remove(this._onDisposeObserver);
  9854. }
  9855. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9856. },
  9857. enumerable: true,
  9858. configurable: true
  9859. });
  9860. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  9861. set: function (callback) {
  9862. if (this._onCollideObserver) {
  9863. this.onCollideObservable.remove(this._onCollideObserver);
  9864. }
  9865. this._onCollideObserver = this.onCollideObservable.add(callback);
  9866. },
  9867. enumerable: true,
  9868. configurable: true
  9869. });
  9870. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  9871. set: function (callback) {
  9872. if (this._onCollisionPositionChangeObserver) {
  9873. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  9874. }
  9875. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  9876. },
  9877. enumerable: true,
  9878. configurable: true
  9879. });
  9880. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  9881. get: function () {
  9882. return this._skeleton;
  9883. },
  9884. set: function (value) {
  9885. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  9886. this._skeleton._unregisterMeshWithPoseMatrix(this);
  9887. }
  9888. if (value && value.needInitialSkinMatrix) {
  9889. value._registerMeshWithPoseMatrix(this);
  9890. }
  9891. this._skeleton = value;
  9892. if (!this._skeleton) {
  9893. this._bonesTransformMatrices = null;
  9894. }
  9895. },
  9896. enumerable: true,
  9897. configurable: true
  9898. });
  9899. /**
  9900. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  9901. */
  9902. AbstractMesh.prototype.toString = function (fullDetails) {
  9903. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  9904. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  9905. if (this._skeleton) {
  9906. ret += ", skeleton: " + this._skeleton.name;
  9907. }
  9908. if (fullDetails) {
  9909. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  9910. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  9911. }
  9912. return ret;
  9913. };
  9914. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  9915. /**
  9916. * Getting the rotation object.
  9917. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  9918. */
  9919. get: function () {
  9920. return this._rotation;
  9921. },
  9922. set: function (newRotation) {
  9923. this._rotation = newRotation;
  9924. },
  9925. enumerable: true,
  9926. configurable: true
  9927. });
  9928. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  9929. get: function () {
  9930. return this._scaling;
  9931. },
  9932. set: function (newScaling) {
  9933. this._scaling = newScaling;
  9934. if (this.physicsImpostor) {
  9935. this.physicsImpostor.forceUpdate();
  9936. }
  9937. },
  9938. enumerable: true,
  9939. configurable: true
  9940. });
  9941. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  9942. get: function () {
  9943. return this._rotationQuaternion;
  9944. },
  9945. set: function (quaternion) {
  9946. this._rotationQuaternion = quaternion;
  9947. //reset the rotation vector.
  9948. if (quaternion && this.rotation.length()) {
  9949. this.rotation.copyFromFloats(0, 0, 0);
  9950. }
  9951. },
  9952. enumerable: true,
  9953. configurable: true
  9954. });
  9955. // Methods
  9956. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  9957. this._poseMatrix.copyFrom(matrix);
  9958. };
  9959. AbstractMesh.prototype.getPoseMatrix = function () {
  9960. return this._poseMatrix;
  9961. };
  9962. AbstractMesh.prototype.disableEdgesRendering = function () {
  9963. if (this._edgesRenderer !== undefined) {
  9964. this._edgesRenderer.dispose();
  9965. this._edgesRenderer = undefined;
  9966. }
  9967. };
  9968. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  9969. if (epsilon === void 0) { epsilon = 0.95; }
  9970. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  9971. this.disableEdgesRendering();
  9972. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  9973. };
  9974. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9975. get: function () {
  9976. return false;
  9977. },
  9978. enumerable: true,
  9979. configurable: true
  9980. });
  9981. AbstractMesh.prototype.getLOD = function (camera) {
  9982. return this;
  9983. };
  9984. AbstractMesh.prototype.getTotalVertices = function () {
  9985. return 0;
  9986. };
  9987. AbstractMesh.prototype.getIndices = function () {
  9988. return null;
  9989. };
  9990. AbstractMesh.prototype.getVerticesData = function (kind) {
  9991. return null;
  9992. };
  9993. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9994. return false;
  9995. };
  9996. AbstractMesh.prototype.getBoundingInfo = function () {
  9997. if (this._masterMesh) {
  9998. return this._masterMesh.getBoundingInfo();
  9999. }
  10000. if (!this._boundingInfo) {
  10001. this._updateBoundingInfo();
  10002. }
  10003. return this._boundingInfo;
  10004. };
  10005. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10006. this._boundingInfo = boundingInfo;
  10007. };
  10008. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10009. get: function () {
  10010. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10011. },
  10012. enumerable: true,
  10013. configurable: true
  10014. });
  10015. AbstractMesh.prototype._preActivate = function () {
  10016. };
  10017. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10018. };
  10019. AbstractMesh.prototype._activate = function (renderId) {
  10020. this._renderId = renderId;
  10021. };
  10022. AbstractMesh.prototype.getWorldMatrix = function () {
  10023. if (this._masterMesh) {
  10024. return this._masterMesh.getWorldMatrix();
  10025. }
  10026. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10027. this.computeWorldMatrix();
  10028. }
  10029. return this._worldMatrix;
  10030. };
  10031. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10032. get: function () {
  10033. return this._worldMatrix;
  10034. },
  10035. enumerable: true,
  10036. configurable: true
  10037. });
  10038. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10039. get: function () {
  10040. return this._absolutePosition;
  10041. },
  10042. enumerable: true,
  10043. configurable: true
  10044. });
  10045. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10046. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10047. this.computeWorldMatrix(true);
  10048. this._isWorldMatrixFrozen = true;
  10049. };
  10050. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10051. this._isWorldMatrixFrozen = false;
  10052. this.computeWorldMatrix(true);
  10053. };
  10054. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10055. get: function () {
  10056. return this._isWorldMatrixFrozen;
  10057. },
  10058. enumerable: true,
  10059. configurable: true
  10060. });
  10061. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10062. axis.normalize();
  10063. if (!this.rotationQuaternion) {
  10064. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10065. this.rotation = BABYLON.Vector3.Zero();
  10066. }
  10067. var rotationQuaternion;
  10068. if (!space || space === BABYLON.Space.LOCAL) {
  10069. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10070. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10071. }
  10072. else {
  10073. if (this.parent) {
  10074. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10075. invertParentWorldMatrix.invert();
  10076. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10077. }
  10078. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10079. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10080. }
  10081. };
  10082. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10083. var displacementVector = axis.scale(distance);
  10084. if (!space || space === BABYLON.Space.LOCAL) {
  10085. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10086. this.setPositionWithLocalVector(tempV3);
  10087. }
  10088. else {
  10089. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10090. }
  10091. };
  10092. AbstractMesh.prototype.getAbsolutePosition = function () {
  10093. this.computeWorldMatrix();
  10094. return this._absolutePosition;
  10095. };
  10096. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10097. if (!absolutePosition) {
  10098. return;
  10099. }
  10100. var absolutePositionX;
  10101. var absolutePositionY;
  10102. var absolutePositionZ;
  10103. if (absolutePosition.x === undefined) {
  10104. if (arguments.length < 3) {
  10105. return;
  10106. }
  10107. absolutePositionX = arguments[0];
  10108. absolutePositionY = arguments[1];
  10109. absolutePositionZ = arguments[2];
  10110. }
  10111. else {
  10112. absolutePositionX = absolutePosition.x;
  10113. absolutePositionY = absolutePosition.y;
  10114. absolutePositionZ = absolutePosition.z;
  10115. }
  10116. if (this.parent) {
  10117. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10118. invertParentWorldMatrix.invert();
  10119. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10120. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10121. }
  10122. else {
  10123. this.position.x = absolutePositionX;
  10124. this.position.y = absolutePositionY;
  10125. this.position.z = absolutePositionZ;
  10126. }
  10127. };
  10128. // ================================== Point of View Movement =================================
  10129. /**
  10130. * Perform relative position change from the point of view of behind the front of the mesh.
  10131. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10132. * Supports definition of mesh facing forward or backward.
  10133. * @param {number} amountRight
  10134. * @param {number} amountUp
  10135. * @param {number} amountForward
  10136. */
  10137. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10138. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10139. };
  10140. /**
  10141. * Calculate relative position change from the point of view of behind the front of the mesh.
  10142. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10143. * Supports definition of mesh facing forward or backward.
  10144. * @param {number} amountRight
  10145. * @param {number} amountUp
  10146. * @param {number} amountForward
  10147. */
  10148. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10149. var rotMatrix = new BABYLON.Matrix();
  10150. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10151. rotQuaternion.toRotationMatrix(rotMatrix);
  10152. var translationDelta = BABYLON.Vector3.Zero();
  10153. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10154. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10155. return translationDelta;
  10156. };
  10157. // ================================== Point of View Rotation =================================
  10158. /**
  10159. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10160. * Supports definition of mesh facing forward or backward.
  10161. * @param {number} flipBack
  10162. * @param {number} twirlClockwise
  10163. * @param {number} tiltRight
  10164. */
  10165. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10166. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10167. };
  10168. /**
  10169. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10170. * Supports definition of mesh facing forward or backward.
  10171. * @param {number} flipBack
  10172. * @param {number} twirlClockwise
  10173. * @param {number} tiltRight
  10174. */
  10175. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10176. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10177. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10178. };
  10179. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10180. this._pivotMatrix = matrix;
  10181. this._cache.pivotMatrixUpdated = true;
  10182. };
  10183. AbstractMesh.prototype.getPivotMatrix = function () {
  10184. return this._pivotMatrix;
  10185. };
  10186. AbstractMesh.prototype._isSynchronized = function () {
  10187. if (this._isDirty) {
  10188. return false;
  10189. }
  10190. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10191. return false;
  10192. if (this._cache.pivotMatrixUpdated) {
  10193. return false;
  10194. }
  10195. if (this.infiniteDistance) {
  10196. return false;
  10197. }
  10198. if (!this._cache.position.equals(this.position))
  10199. return false;
  10200. if (this.rotationQuaternion) {
  10201. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10202. return false;
  10203. }
  10204. if (!this._cache.rotation.equals(this.rotation))
  10205. return false;
  10206. if (!this._cache.scaling.equals(this.scaling))
  10207. return false;
  10208. return true;
  10209. };
  10210. AbstractMesh.prototype._initCache = function () {
  10211. _super.prototype._initCache.call(this);
  10212. this._cache.localMatrixUpdated = false;
  10213. this._cache.position = BABYLON.Vector3.Zero();
  10214. this._cache.scaling = BABYLON.Vector3.Zero();
  10215. this._cache.rotation = BABYLON.Vector3.Zero();
  10216. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10217. this._cache.billboardMode = -1;
  10218. };
  10219. AbstractMesh.prototype.markAsDirty = function (property) {
  10220. if (property === "rotation") {
  10221. this.rotationQuaternion = null;
  10222. }
  10223. this._currentRenderId = Number.MAX_VALUE;
  10224. this._isDirty = true;
  10225. };
  10226. AbstractMesh.prototype._updateBoundingInfo = function () {
  10227. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10228. this._boundingInfo.update(this.worldMatrixFromCache);
  10229. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10230. };
  10231. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10232. if (!this.subMeshes) {
  10233. return;
  10234. }
  10235. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10236. var subMesh = this.subMeshes[subIndex];
  10237. if (!subMesh.IsGlobal) {
  10238. subMesh.updateBoundingInfo(matrix);
  10239. }
  10240. }
  10241. };
  10242. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10243. if (this._isWorldMatrixFrozen) {
  10244. return this._worldMatrix;
  10245. }
  10246. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10247. this._currentRenderId = this.getScene().getRenderId();
  10248. return this._worldMatrix;
  10249. }
  10250. this._cache.position.copyFrom(this.position);
  10251. this._cache.scaling.copyFrom(this.scaling);
  10252. this._cache.pivotMatrixUpdated = false;
  10253. this._cache.billboardMode = this.billboardMode;
  10254. this._currentRenderId = this.getScene().getRenderId();
  10255. this._isDirty = false;
  10256. // Scaling
  10257. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10258. // Rotation
  10259. //rotate, if quaternion is set and rotation was used
  10260. if (this.rotationQuaternion) {
  10261. var len = this.rotation.length();
  10262. if (len) {
  10263. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10264. this.rotation.copyFromFloats(0, 0, 0);
  10265. }
  10266. }
  10267. if (this.rotationQuaternion) {
  10268. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10269. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10270. }
  10271. else {
  10272. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10273. this._cache.rotation.copyFrom(this.rotation);
  10274. }
  10275. // Translation
  10276. if (this.infiniteDistance && !this.parent) {
  10277. var camera = this.getScene().activeCamera;
  10278. if (camera) {
  10279. var cameraWorldMatrix = camera.getWorldMatrix();
  10280. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10281. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10282. }
  10283. }
  10284. else {
  10285. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10286. }
  10287. // Composing transformations
  10288. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10289. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10290. // Billboarding
  10291. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10292. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10293. var localPosition = BABYLON.Tmp.Vector3[0];
  10294. if (this.parent && this.parent.getWorldMatrix) {
  10295. this._markSyncedWithParent();
  10296. var parentMatrix;
  10297. if (this._meshToBoneReferal) {
  10298. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10299. parentMatrix = BABYLON.Tmp.Matrix[6];
  10300. }
  10301. else {
  10302. parentMatrix = this.parent.getWorldMatrix();
  10303. }
  10304. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10305. localPosition = BABYLON.Tmp.Vector3[1];
  10306. }
  10307. var zero = this.getScene().activeCamera.globalPosition.clone();
  10308. if (this.parent && this.parent.position) {
  10309. localPosition.addInPlace(this.parent.position);
  10310. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10311. }
  10312. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10313. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10314. zero.x = localPosition.x + BABYLON.Epsilon;
  10315. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10316. zero.y = localPosition.y + BABYLON.Epsilon;
  10317. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10318. zero.z = localPosition.z + BABYLON.Epsilon;
  10319. }
  10320. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10321. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10322. BABYLON.Tmp.Matrix[3].invert();
  10323. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10324. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10325. }
  10326. // Local world
  10327. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10328. // Parent
  10329. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10330. this._markSyncedWithParent();
  10331. if (this._meshToBoneReferal) {
  10332. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10333. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10334. }
  10335. else {
  10336. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10337. }
  10338. }
  10339. else {
  10340. this._worldMatrix.copyFrom(this._localWorld);
  10341. }
  10342. // Bounding info
  10343. this._updateBoundingInfo();
  10344. // Absolute position
  10345. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10346. // Callbacks
  10347. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10348. if (!this._poseMatrix) {
  10349. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10350. }
  10351. return this._worldMatrix;
  10352. };
  10353. /**
  10354. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10355. * @param func: callback function to add
  10356. */
  10357. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10358. this.onAfterWorldMatrixUpdateObservable.add(func);
  10359. };
  10360. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10361. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10362. };
  10363. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10364. this.computeWorldMatrix();
  10365. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10366. };
  10367. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10368. this.computeWorldMatrix();
  10369. var invLocalWorldMatrix = this._localWorld.clone();
  10370. invLocalWorldMatrix.invert();
  10371. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10372. };
  10373. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10374. this.computeWorldMatrix(true);
  10375. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10376. };
  10377. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10378. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10379. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10380. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10381. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10382. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10383. /// <returns>Mesh oriented towards targetMesh</returns>
  10384. if (yawCor === void 0) { yawCor = 0; }
  10385. if (pitchCor === void 0) { pitchCor = 0; }
  10386. if (rollCor === void 0) { rollCor = 0; }
  10387. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10388. var dv = AbstractMesh._lookAtVectorCache;
  10389. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10390. targetPoint.subtractToRef(pos, dv);
  10391. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10392. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10393. var pitch = Math.atan2(dv.y, len);
  10394. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10395. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10396. };
  10397. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10398. this._meshToBoneReferal = affectedMesh;
  10399. this.parent = bone;
  10400. if (bone.getWorldMatrix().determinant() < 0) {
  10401. this.scalingDeterminant *= -1;
  10402. }
  10403. };
  10404. AbstractMesh.prototype.detachFromBone = function () {
  10405. if (this.parent.getWorldMatrix().determinant() < 0) {
  10406. this.scalingDeterminant *= -1;
  10407. }
  10408. this._meshToBoneReferal = null;
  10409. this.parent = null;
  10410. };
  10411. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10412. return this._boundingInfo.isInFrustum(frustumPlanes);
  10413. };
  10414. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10415. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10416. ;
  10417. };
  10418. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10419. if (!this._boundingInfo || !mesh._boundingInfo) {
  10420. return false;
  10421. }
  10422. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10423. };
  10424. AbstractMesh.prototype.intersectsPoint = function (point) {
  10425. if (!this._boundingInfo) {
  10426. return false;
  10427. }
  10428. return this._boundingInfo.intersectsPoint(point);
  10429. };
  10430. // Physics
  10431. /**
  10432. * @Deprecated. Use new PhysicsImpostor instead.
  10433. * */
  10434. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10435. //legacy support
  10436. if (impostor.impostor) {
  10437. options = impostor;
  10438. impostor = impostor.impostor;
  10439. }
  10440. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10441. return this.physicsImpostor.physicsBody;
  10442. };
  10443. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10444. return this.physicsImpostor;
  10445. };
  10446. /**
  10447. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10448. */
  10449. AbstractMesh.prototype.getPhysicsMass = function () {
  10450. return this.physicsImpostor.getParam("mass");
  10451. };
  10452. /**
  10453. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10454. */
  10455. AbstractMesh.prototype.getPhysicsFriction = function () {
  10456. return this.physicsImpostor.getParam("friction");
  10457. };
  10458. /**
  10459. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10460. */
  10461. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10462. return this.physicsImpostor.getParam("restitution");
  10463. };
  10464. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10465. if (!camera) {
  10466. camera = this.getScene().activeCamera;
  10467. }
  10468. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10469. };
  10470. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10471. if (!camera) {
  10472. camera = this.getScene().activeCamera;
  10473. }
  10474. return this.absolutePosition.subtract(camera.position).length();
  10475. };
  10476. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10477. if (!this.physicsImpostor) {
  10478. return;
  10479. }
  10480. this.physicsImpostor.applyImpulse(force, contactPoint);
  10481. };
  10482. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10483. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10484. return;
  10485. }
  10486. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10487. mainPivot: pivot1,
  10488. connectedPivot: pivot2,
  10489. nativeParams: options
  10490. });
  10491. };
  10492. /**
  10493. * @Deprecated
  10494. */
  10495. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10496. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10497. this.updatePhysicsBody();
  10498. };
  10499. /**
  10500. * @Deprecated
  10501. * Calling this function is not needed anymore.
  10502. * The physics engine takes care of transofmration automatically.
  10503. */
  10504. AbstractMesh.prototype.updatePhysicsBody = function () {
  10505. //Unneeded
  10506. };
  10507. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10508. // Collisions
  10509. get: function () {
  10510. return this._checkCollisions;
  10511. },
  10512. set: function (collisionEnabled) {
  10513. this._checkCollisions = collisionEnabled;
  10514. if (this.getScene().workerCollisions) {
  10515. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10516. }
  10517. },
  10518. enumerable: true,
  10519. configurable: true
  10520. });
  10521. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10522. var globalPosition = this.getAbsolutePosition();
  10523. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10524. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10525. this._collider.radius = this.ellipsoid;
  10526. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10527. };
  10528. // Submeshes octree
  10529. /**
  10530. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10531. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10532. */
  10533. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10534. if (maxCapacity === void 0) { maxCapacity = 64; }
  10535. if (maxDepth === void 0) { maxDepth = 2; }
  10536. if (!this._submeshesOctree) {
  10537. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10538. }
  10539. this.computeWorldMatrix(true);
  10540. // Update octree
  10541. var bbox = this.getBoundingInfo().boundingBox;
  10542. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10543. return this._submeshesOctree;
  10544. };
  10545. // Collisions
  10546. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10547. this._generatePointsArray();
  10548. // Transformation
  10549. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10550. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10551. subMesh._lastColliderWorldVertices = [];
  10552. subMesh._trianglePlanes = [];
  10553. var start = subMesh.verticesStart;
  10554. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10555. for (var i = start; i < end; i++) {
  10556. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10557. }
  10558. }
  10559. // Collide
  10560. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10561. if (collider.collisionFound) {
  10562. collider.collidedMesh = this;
  10563. }
  10564. };
  10565. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10566. var subMeshes;
  10567. var len;
  10568. // Octrees
  10569. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10570. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10571. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10572. len = intersections.length;
  10573. subMeshes = intersections.data;
  10574. }
  10575. else {
  10576. subMeshes = this.subMeshes;
  10577. len = subMeshes.length;
  10578. }
  10579. for (var index = 0; index < len; index++) {
  10580. var subMesh = subMeshes[index];
  10581. // Bounding test
  10582. if (len > 1 && !subMesh._checkCollision(collider))
  10583. continue;
  10584. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10585. }
  10586. };
  10587. AbstractMesh.prototype._checkCollision = function (collider) {
  10588. // Bounding box test
  10589. if (!this._boundingInfo._checkCollision(collider))
  10590. return;
  10591. // Transformation matrix
  10592. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10593. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10594. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10595. };
  10596. // Picking
  10597. AbstractMesh.prototype._generatePointsArray = function () {
  10598. return false;
  10599. };
  10600. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10601. var pickingInfo = new BABYLON.PickingInfo();
  10602. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10603. return pickingInfo;
  10604. }
  10605. if (!this._generatePointsArray()) {
  10606. return pickingInfo;
  10607. }
  10608. var intersectInfo = null;
  10609. // Octrees
  10610. var subMeshes;
  10611. var len;
  10612. if (this._submeshesOctree && this.useOctreeForPicking) {
  10613. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10614. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10615. len = intersections.length;
  10616. subMeshes = intersections.data;
  10617. }
  10618. else {
  10619. subMeshes = this.subMeshes;
  10620. len = subMeshes.length;
  10621. }
  10622. for (var index = 0; index < len; index++) {
  10623. var subMesh = subMeshes[index];
  10624. // Bounding test
  10625. if (len > 1 && !subMesh.canIntersects(ray))
  10626. continue;
  10627. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10628. if (currentIntersectInfo) {
  10629. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10630. intersectInfo = currentIntersectInfo;
  10631. intersectInfo.subMeshId = index;
  10632. if (fastCheck) {
  10633. break;
  10634. }
  10635. }
  10636. }
  10637. }
  10638. if (intersectInfo) {
  10639. // Get picked point
  10640. var world = this.getWorldMatrix();
  10641. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10642. var direction = ray.direction.clone();
  10643. direction = direction.scale(intersectInfo.distance);
  10644. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10645. var pickedPoint = worldOrigin.add(worldDirection);
  10646. // Return result
  10647. pickingInfo.hit = true;
  10648. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10649. pickingInfo.pickedPoint = pickedPoint;
  10650. pickingInfo.pickedMesh = this;
  10651. pickingInfo.bu = intersectInfo.bu;
  10652. pickingInfo.bv = intersectInfo.bv;
  10653. pickingInfo.faceId = intersectInfo.faceId;
  10654. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10655. return pickingInfo;
  10656. }
  10657. return pickingInfo;
  10658. };
  10659. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10660. return null;
  10661. };
  10662. AbstractMesh.prototype.releaseSubMeshes = function () {
  10663. if (this.subMeshes) {
  10664. while (this.subMeshes.length) {
  10665. this.subMeshes[0].dispose();
  10666. }
  10667. }
  10668. else {
  10669. this.subMeshes = new Array();
  10670. }
  10671. };
  10672. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10673. var _this = this;
  10674. var index;
  10675. // Action manager
  10676. if (this.actionManager) {
  10677. this.actionManager.dispose();
  10678. this.actionManager = null;
  10679. }
  10680. // Skeleton
  10681. this.skeleton = null;
  10682. // Animations
  10683. this.getScene().stopAnimation(this);
  10684. // Physics
  10685. if (this.physicsImpostor) {
  10686. this.physicsImpostor.dispose();
  10687. }
  10688. // Intersections in progress
  10689. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10690. var other = this._intersectionsInProgress[index];
  10691. var pos = other._intersectionsInProgress.indexOf(this);
  10692. other._intersectionsInProgress.splice(pos, 1);
  10693. }
  10694. this._intersectionsInProgress = [];
  10695. // Lights
  10696. var lights = this.getScene().lights;
  10697. lights.forEach(function (light) {
  10698. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  10699. if (meshIndex !== -1) {
  10700. light.includedOnlyMeshes.splice(meshIndex, 1);
  10701. }
  10702. meshIndex = light.excludedMeshes.indexOf(_this);
  10703. if (meshIndex !== -1) {
  10704. light.excludedMeshes.splice(meshIndex, 1);
  10705. }
  10706. });
  10707. // Edges
  10708. if (this._edgesRenderer) {
  10709. this._edgesRenderer.dispose();
  10710. this._edgesRenderer = null;
  10711. }
  10712. // SubMeshes
  10713. this.releaseSubMeshes();
  10714. // Remove from scene
  10715. this.getScene().removeMesh(this);
  10716. if (!doNotRecurse) {
  10717. // Particles
  10718. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10719. if (this.getScene().particleSystems[index].emitter === this) {
  10720. this.getScene().particleSystems[index].dispose();
  10721. index--;
  10722. }
  10723. }
  10724. // Children
  10725. var objects = this.getDescendants(true);
  10726. for (index = 0; index < objects.length; index++) {
  10727. objects[index].dispose();
  10728. }
  10729. }
  10730. else {
  10731. var childMeshes = this.getChildMeshes(true);
  10732. for (index = 0; index < childMeshes.length; index++) {
  10733. var child = childMeshes[index];
  10734. child.parent = null;
  10735. child.computeWorldMatrix(true);
  10736. }
  10737. }
  10738. _super.prototype.dispose.call(this);
  10739. this.onAfterWorldMatrixUpdateObservable.clear();
  10740. this.onCollideObservable.clear();
  10741. this.onCollisionPositionChangeObservable.clear();
  10742. this._isDisposed = true;
  10743. // Callback
  10744. this.onDisposeObservable.notifyObservers(this);
  10745. this.onDisposeObservable.clear();
  10746. };
  10747. // Statics
  10748. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10749. AbstractMesh._BILLBOARDMODE_X = 1;
  10750. AbstractMesh._BILLBOARDMODE_Y = 2;
  10751. AbstractMesh._BILLBOARDMODE_Z = 4;
  10752. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10753. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  10754. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  10755. return AbstractMesh;
  10756. }(BABYLON.Node));
  10757. BABYLON.AbstractMesh = AbstractMesh;
  10758. })(BABYLON || (BABYLON = {}));
  10759. var BABYLON;
  10760. (function (BABYLON) {
  10761. var Light = (function (_super) {
  10762. __extends(Light, _super);
  10763. function Light(name, scene) {
  10764. _super.call(this, name, scene);
  10765. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  10766. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  10767. this.intensity = 1.0;
  10768. this.range = Number.MAX_VALUE;
  10769. this.includeOnlyWithLayerMask = 0;
  10770. this.includedOnlyMeshes = new Array();
  10771. this.excludedMeshes = new Array();
  10772. this.excludeWithLayerMask = 0;
  10773. // PBR Properties.
  10774. this.radius = 0.00001;
  10775. this._excludedMeshesIds = new Array();
  10776. this._includedOnlyMeshesIds = new Array();
  10777. scene.addLight(this);
  10778. }
  10779. /**
  10780. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10781. */
  10782. Light.prototype.toString = function (fullDetails) {
  10783. var ret = "Name: " + this.name;
  10784. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  10785. if (this.animations) {
  10786. for (var i = 0; i < this.animations.length; i++) {
  10787. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  10788. }
  10789. }
  10790. if (fullDetails) {
  10791. }
  10792. return ret;
  10793. };
  10794. Light.prototype.getShadowGenerator = function () {
  10795. return this._shadowGenerator;
  10796. };
  10797. Light.prototype.getAbsolutePosition = function () {
  10798. return BABYLON.Vector3.Zero();
  10799. };
  10800. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  10801. };
  10802. Light.prototype._getWorldMatrix = function () {
  10803. return BABYLON.Matrix.Identity();
  10804. };
  10805. Light.prototype.canAffectMesh = function (mesh) {
  10806. if (!mesh) {
  10807. return true;
  10808. }
  10809. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  10810. return false;
  10811. }
  10812. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  10813. return false;
  10814. }
  10815. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  10816. return false;
  10817. }
  10818. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  10819. return false;
  10820. }
  10821. return true;
  10822. };
  10823. Light.prototype.getWorldMatrix = function () {
  10824. this._currentRenderId = this.getScene().getRenderId();
  10825. var worldMatrix = this._getWorldMatrix();
  10826. if (this.parent && this.parent.getWorldMatrix) {
  10827. if (!this._parentedWorldMatrix) {
  10828. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  10829. }
  10830. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  10831. this._markSyncedWithParent();
  10832. return this._parentedWorldMatrix;
  10833. }
  10834. return worldMatrix;
  10835. };
  10836. Light.prototype.dispose = function () {
  10837. if (this._shadowGenerator) {
  10838. this._shadowGenerator.dispose();
  10839. this._shadowGenerator = null;
  10840. }
  10841. // Animations
  10842. this.getScene().stopAnimation(this);
  10843. // Remove from scene
  10844. this.getScene().removeLight(this);
  10845. _super.prototype.dispose.call(this);
  10846. };
  10847. Light.prototype.getTypeID = function () {
  10848. return 0;
  10849. };
  10850. Light.prototype.clone = function (name) {
  10851. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  10852. };
  10853. Light.prototype.serialize = function () {
  10854. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  10855. // Type
  10856. serializationObject.type = this.getTypeID();
  10857. // Parent
  10858. if (this.parent) {
  10859. serializationObject.parentId = this.parent.id;
  10860. }
  10861. // Inclusion / exclusions
  10862. if (this.excludedMeshes.length > 0) {
  10863. serializationObject.excludedMeshesIds = [];
  10864. this.excludedMeshes.forEach(function (mesh) {
  10865. serializationObject.excludedMeshesIds.push(mesh.id);
  10866. });
  10867. }
  10868. if (this.includedOnlyMeshes.length > 0) {
  10869. serializationObject.includedOnlyMeshesIds = [];
  10870. this.includedOnlyMeshes.forEach(function (mesh) {
  10871. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  10872. });
  10873. }
  10874. // Animations
  10875. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  10876. serializationObject.ranges = this.serializeAnimationRanges();
  10877. return serializationObject;
  10878. };
  10879. Light.GetConstructorFromName = function (type, name, scene) {
  10880. switch (type) {
  10881. case 0:
  10882. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  10883. case 1:
  10884. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  10885. case 2:
  10886. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  10887. case 3:
  10888. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  10889. }
  10890. };
  10891. Light.Parse = function (parsedLight, scene) {
  10892. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  10893. // Inclusion / exclusions
  10894. if (parsedLight.excludedMeshesIds) {
  10895. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  10896. }
  10897. if (parsedLight.includedOnlyMeshesIds) {
  10898. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  10899. }
  10900. // Parent
  10901. if (parsedLight.parentId) {
  10902. light._waitingParentId = parsedLight.parentId;
  10903. }
  10904. // Animations
  10905. if (parsedLight.animations) {
  10906. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  10907. var parsedAnimation = parsedLight.animations[animationIndex];
  10908. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  10909. }
  10910. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  10911. }
  10912. if (parsedLight.autoAnimate) {
  10913. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  10914. }
  10915. return light;
  10916. };
  10917. __decorate([
  10918. BABYLON.serializeAsColor3()
  10919. ], Light.prototype, "diffuse", void 0);
  10920. __decorate([
  10921. BABYLON.serializeAsColor3()
  10922. ], Light.prototype, "specular", void 0);
  10923. __decorate([
  10924. BABYLON.serialize()
  10925. ], Light.prototype, "intensity", void 0);
  10926. __decorate([
  10927. BABYLON.serialize()
  10928. ], Light.prototype, "range", void 0);
  10929. __decorate([
  10930. BABYLON.serialize()
  10931. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  10932. __decorate([
  10933. BABYLON.serialize()
  10934. ], Light.prototype, "excludeWithLayerMask", void 0);
  10935. __decorate([
  10936. BABYLON.serialize()
  10937. ], Light.prototype, "radius", void 0);
  10938. return Light;
  10939. }(BABYLON.Node));
  10940. BABYLON.Light = Light;
  10941. })(BABYLON || (BABYLON = {}));
  10942. var BABYLON;
  10943. (function (BABYLON) {
  10944. var PointLight = (function (_super) {
  10945. __extends(PointLight, _super);
  10946. function PointLight(name, position, scene) {
  10947. _super.call(this, name, scene);
  10948. this.position = position;
  10949. }
  10950. PointLight.prototype.getAbsolutePosition = function () {
  10951. return this.transformedPosition ? this.transformedPosition : this.position;
  10952. };
  10953. PointLight.prototype.computeTransformedPosition = function () {
  10954. if (this.parent && this.parent.getWorldMatrix) {
  10955. if (!this.transformedPosition) {
  10956. this.transformedPosition = BABYLON.Vector3.Zero();
  10957. }
  10958. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  10959. return true;
  10960. }
  10961. return false;
  10962. };
  10963. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  10964. if (this.parent && this.parent.getWorldMatrix) {
  10965. this.computeTransformedPosition();
  10966. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  10967. return;
  10968. }
  10969. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  10970. };
  10971. PointLight.prototype.needCube = function () {
  10972. return true;
  10973. };
  10974. PointLight.prototype.supportsVSM = function () {
  10975. return false;
  10976. };
  10977. PointLight.prototype.needRefreshPerFrame = function () {
  10978. return false;
  10979. };
  10980. PointLight.prototype.getShadowDirection = function (faceIndex) {
  10981. switch (faceIndex) {
  10982. case 0:
  10983. return new BABYLON.Vector3(1, 0, 0);
  10984. case 1:
  10985. return new BABYLON.Vector3(-1, 0, 0);
  10986. case 2:
  10987. return new BABYLON.Vector3(0, -1, 0);
  10988. case 3:
  10989. return new BABYLON.Vector3(0, 1, 0);
  10990. case 4:
  10991. return new BABYLON.Vector3(0, 0, 1);
  10992. case 5:
  10993. return new BABYLON.Vector3(0, 0, -1);
  10994. }
  10995. return BABYLON.Vector3.Zero();
  10996. };
  10997. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  10998. var activeCamera = this.getScene().activeCamera;
  10999. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11000. };
  11001. PointLight.prototype._getWorldMatrix = function () {
  11002. if (!this._worldMatrix) {
  11003. this._worldMatrix = BABYLON.Matrix.Identity();
  11004. }
  11005. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11006. return this._worldMatrix;
  11007. };
  11008. PointLight.prototype.getTypeID = function () {
  11009. return 0;
  11010. };
  11011. __decorate([
  11012. BABYLON.serializeAsVector3()
  11013. ], PointLight.prototype, "position", void 0);
  11014. return PointLight;
  11015. }(BABYLON.Light));
  11016. BABYLON.PointLight = PointLight;
  11017. })(BABYLON || (BABYLON = {}));
  11018. var BABYLON;
  11019. (function (BABYLON) {
  11020. var SpotLight = (function (_super) {
  11021. __extends(SpotLight, _super);
  11022. function SpotLight(name, position, direction, angle, exponent, scene) {
  11023. _super.call(this, name, scene);
  11024. this.position = position;
  11025. this.direction = direction;
  11026. this.angle = angle;
  11027. this.exponent = exponent;
  11028. }
  11029. SpotLight.prototype.getAbsolutePosition = function () {
  11030. return this.transformedPosition ? this.transformedPosition : this.position;
  11031. };
  11032. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11033. var activeCamera = this.getScene().activeCamera;
  11034. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11035. };
  11036. SpotLight.prototype.needCube = function () {
  11037. return false;
  11038. };
  11039. SpotLight.prototype.supportsVSM = function () {
  11040. return true;
  11041. };
  11042. SpotLight.prototype.needRefreshPerFrame = function () {
  11043. return false;
  11044. };
  11045. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11046. return this.direction;
  11047. };
  11048. SpotLight.prototype.setDirectionToTarget = function (target) {
  11049. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11050. return this.direction;
  11051. };
  11052. SpotLight.prototype.computeTransformedPosition = function () {
  11053. if (this.parent && this.parent.getWorldMatrix) {
  11054. if (!this.transformedPosition) {
  11055. this.transformedPosition = BABYLON.Vector3.Zero();
  11056. }
  11057. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11058. return true;
  11059. }
  11060. return false;
  11061. };
  11062. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11063. var normalizeDirection;
  11064. if (this.parent && this.parent.getWorldMatrix) {
  11065. if (!this._transformedDirection) {
  11066. this._transformedDirection = BABYLON.Vector3.Zero();
  11067. }
  11068. this.computeTransformedPosition();
  11069. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11070. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11071. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11072. }
  11073. else {
  11074. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11075. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11076. }
  11077. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11078. };
  11079. SpotLight.prototype._getWorldMatrix = function () {
  11080. if (!this._worldMatrix) {
  11081. this._worldMatrix = BABYLON.Matrix.Identity();
  11082. }
  11083. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11084. return this._worldMatrix;
  11085. };
  11086. SpotLight.prototype.getTypeID = function () {
  11087. return 2;
  11088. };
  11089. __decorate([
  11090. BABYLON.serializeAsVector3()
  11091. ], SpotLight.prototype, "position", void 0);
  11092. __decorate([
  11093. BABYLON.serializeAsVector3()
  11094. ], SpotLight.prototype, "direction", void 0);
  11095. __decorate([
  11096. BABYLON.serialize()
  11097. ], SpotLight.prototype, "angle", void 0);
  11098. __decorate([
  11099. BABYLON.serialize()
  11100. ], SpotLight.prototype, "exponent", void 0);
  11101. return SpotLight;
  11102. }(BABYLON.Light));
  11103. BABYLON.SpotLight = SpotLight;
  11104. })(BABYLON || (BABYLON = {}));
  11105. var BABYLON;
  11106. (function (BABYLON) {
  11107. var HemisphericLight = (function (_super) {
  11108. __extends(HemisphericLight, _super);
  11109. function HemisphericLight(name, direction, scene) {
  11110. _super.call(this, name, scene);
  11111. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11112. this.direction = direction;
  11113. }
  11114. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11115. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11116. return this.direction;
  11117. };
  11118. HemisphericLight.prototype.getShadowGenerator = function () {
  11119. return null;
  11120. };
  11121. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11122. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11123. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11124. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11125. };
  11126. HemisphericLight.prototype._getWorldMatrix = function () {
  11127. if (!this._worldMatrix) {
  11128. this._worldMatrix = BABYLON.Matrix.Identity();
  11129. }
  11130. return this._worldMatrix;
  11131. };
  11132. HemisphericLight.prototype.getTypeID = function () {
  11133. return 3;
  11134. };
  11135. __decorate([
  11136. BABYLON.serializeAsColor3()
  11137. ], HemisphericLight.prototype, "groundColor", void 0);
  11138. __decorate([
  11139. BABYLON.serializeAsVector3()
  11140. ], HemisphericLight.prototype, "direction", void 0);
  11141. return HemisphericLight;
  11142. }(BABYLON.Light));
  11143. BABYLON.HemisphericLight = HemisphericLight;
  11144. })(BABYLON || (BABYLON = {}));
  11145. var BABYLON;
  11146. (function (BABYLON) {
  11147. var DirectionalLight = (function (_super) {
  11148. __extends(DirectionalLight, _super);
  11149. function DirectionalLight(name, direction, scene) {
  11150. _super.call(this, name, scene);
  11151. this.shadowOrthoScale = 0.5;
  11152. this.autoUpdateExtends = true;
  11153. // Cache
  11154. this._orthoLeft = Number.MAX_VALUE;
  11155. this._orthoRight = Number.MIN_VALUE;
  11156. this._orthoTop = Number.MIN_VALUE;
  11157. this._orthoBottom = Number.MAX_VALUE;
  11158. this.position = direction.scale(-1);
  11159. this.direction = direction;
  11160. }
  11161. DirectionalLight.prototype.getAbsolutePosition = function () {
  11162. return this.transformedPosition ? this.transformedPosition : this.position;
  11163. };
  11164. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11165. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11166. return this.direction;
  11167. };
  11168. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11169. var activeCamera = this.getScene().activeCamera;
  11170. // Check extends
  11171. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11172. var tempVector3 = BABYLON.Vector3.Zero();
  11173. this._orthoLeft = Number.MAX_VALUE;
  11174. this._orthoRight = Number.MIN_VALUE;
  11175. this._orthoTop = Number.MIN_VALUE;
  11176. this._orthoBottom = Number.MAX_VALUE;
  11177. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11178. var mesh = renderList[meshIndex];
  11179. if (!mesh) {
  11180. continue;
  11181. }
  11182. var boundingInfo = mesh.getBoundingInfo();
  11183. if (!boundingInfo) {
  11184. continue;
  11185. }
  11186. var boundingBox = boundingInfo.boundingBox;
  11187. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11188. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11189. if (tempVector3.x < this._orthoLeft)
  11190. this._orthoLeft = tempVector3.x;
  11191. if (tempVector3.y < this._orthoBottom)
  11192. this._orthoBottom = tempVector3.y;
  11193. if (tempVector3.x > this._orthoRight)
  11194. this._orthoRight = tempVector3.x;
  11195. if (tempVector3.y > this._orthoTop)
  11196. this._orthoTop = tempVector3.y;
  11197. }
  11198. }
  11199. }
  11200. var xOffset = this._orthoRight - this._orthoLeft;
  11201. var yOffset = this._orthoTop - this._orthoBottom;
  11202. 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);
  11203. };
  11204. DirectionalLight.prototype.supportsVSM = function () {
  11205. return true;
  11206. };
  11207. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11208. return true;
  11209. };
  11210. DirectionalLight.prototype.needCube = function () {
  11211. return false;
  11212. };
  11213. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11214. return this.direction;
  11215. };
  11216. DirectionalLight.prototype.computeTransformedPosition = function () {
  11217. if (this.parent && this.parent.getWorldMatrix) {
  11218. if (!this.transformedPosition) {
  11219. this.transformedPosition = BABYLON.Vector3.Zero();
  11220. }
  11221. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11222. return true;
  11223. }
  11224. return false;
  11225. };
  11226. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11227. if (this.parent && this.parent.getWorldMatrix) {
  11228. if (!this._transformedDirection) {
  11229. this._transformedDirection = BABYLON.Vector3.Zero();
  11230. }
  11231. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11232. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11233. return;
  11234. }
  11235. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11236. };
  11237. DirectionalLight.prototype._getWorldMatrix = function () {
  11238. if (!this._worldMatrix) {
  11239. this._worldMatrix = BABYLON.Matrix.Identity();
  11240. }
  11241. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11242. return this._worldMatrix;
  11243. };
  11244. DirectionalLight.prototype.getTypeID = function () {
  11245. return 1;
  11246. };
  11247. __decorate([
  11248. BABYLON.serializeAsVector3()
  11249. ], DirectionalLight.prototype, "position", void 0);
  11250. __decorate([
  11251. BABYLON.serializeAsVector3()
  11252. ], DirectionalLight.prototype, "direction", void 0);
  11253. __decorate([
  11254. BABYLON.serialize()
  11255. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11256. __decorate([
  11257. BABYLON.serialize()
  11258. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11259. return DirectionalLight;
  11260. }(BABYLON.Light));
  11261. BABYLON.DirectionalLight = DirectionalLight;
  11262. })(BABYLON || (BABYLON = {}));
  11263. var BABYLON;
  11264. (function (BABYLON) {
  11265. var ShadowGenerator = (function () {
  11266. function ShadowGenerator(mapSize, light) {
  11267. var _this = this;
  11268. // Members
  11269. this._filter = ShadowGenerator.FILTER_NONE;
  11270. this.blurScale = 2;
  11271. this._blurBoxOffset = 0;
  11272. this._bias = 0.00005;
  11273. this._lightDirection = BABYLON.Vector3.Zero();
  11274. this.forceBackFacesOnly = false;
  11275. this._darkness = 0;
  11276. this._transparencyShadow = false;
  11277. this._viewMatrix = BABYLON.Matrix.Zero();
  11278. this._projectionMatrix = BABYLON.Matrix.Zero();
  11279. this._transformMatrix = BABYLON.Matrix.Zero();
  11280. this._worldViewProjection = BABYLON.Matrix.Zero();
  11281. this._currentFaceIndex = 0;
  11282. this._currentFaceIndexCache = 0;
  11283. this._useFullFloat = true;
  11284. this._light = light;
  11285. this._scene = light.getScene();
  11286. this._mapSize = mapSize;
  11287. light._shadowGenerator = this;
  11288. // Texture type fallback from float to int if not supported.
  11289. var textureType;
  11290. var caps = this._scene.getEngine().getCaps();
  11291. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11292. this._useFullFloat = true;
  11293. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11294. }
  11295. else {
  11296. this._useFullFloat = false;
  11297. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11298. }
  11299. // Render target
  11300. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11301. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11302. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11303. this._shadowMap.anisotropicFilteringLevel = 1;
  11304. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11305. this._shadowMap.renderParticles = false;
  11306. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11307. _this._currentFaceIndex = faceIndex;
  11308. });
  11309. this._shadowMap.onAfterUnbindObservable.add(function () {
  11310. if (!_this.useBlurVarianceShadowMap) {
  11311. return;
  11312. }
  11313. if (!_this._shadowMap2) {
  11314. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11315. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11316. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11317. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11318. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11319. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11320. effect.setTexture("textureSampler", _this._shadowMap);
  11321. });
  11322. _this.blurBoxOffset = 1;
  11323. }
  11324. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11325. });
  11326. // Custom render function
  11327. var renderSubMesh = function (subMesh) {
  11328. var mesh = subMesh.getRenderingMesh();
  11329. var scene = _this._scene;
  11330. var engine = scene.getEngine();
  11331. // Culling
  11332. engine.setState(subMesh.getMaterial().backFaceCulling);
  11333. // Managing instances
  11334. var batch = mesh._getInstancesRenderList(subMesh._id);
  11335. if (batch.mustReturn) {
  11336. return;
  11337. }
  11338. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11339. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11340. engine.enableEffect(_this._effect);
  11341. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11342. var material = subMesh.getMaterial();
  11343. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11344. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11345. if (_this.getLight().needCube()) {
  11346. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11347. }
  11348. // Alpha test
  11349. if (material && material.needAlphaTesting()) {
  11350. var alphaTexture = material.getAlphaTestTexture();
  11351. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11352. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11353. }
  11354. // Bones
  11355. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11356. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11357. }
  11358. if (_this.forceBackFacesOnly) {
  11359. engine.setState(true, 0, false, true);
  11360. }
  11361. // Draw
  11362. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11363. if (_this.forceBackFacesOnly) {
  11364. engine.setState(true, 0, false, false);
  11365. }
  11366. }
  11367. else {
  11368. // Need to reset refresh rate of the shadowMap
  11369. _this._shadowMap.resetRefreshCounter();
  11370. }
  11371. };
  11372. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11373. var index;
  11374. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11375. renderSubMesh(opaqueSubMeshes.data[index]);
  11376. }
  11377. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11378. renderSubMesh(alphaTestSubMeshes.data[index]);
  11379. }
  11380. if (_this._transparencyShadow) {
  11381. for (index = 0; index < transparentSubMeshes.length; index++) {
  11382. renderSubMesh(transparentSubMeshes.data[index]);
  11383. }
  11384. }
  11385. };
  11386. this._shadowMap.onClearObservable.add(function (engine) {
  11387. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11388. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11389. }
  11390. else {
  11391. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11392. }
  11393. });
  11394. }
  11395. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11396. // Static
  11397. get: function () {
  11398. return ShadowGenerator._FILTER_NONE;
  11399. },
  11400. enumerable: true,
  11401. configurable: true
  11402. });
  11403. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11404. get: function () {
  11405. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11406. },
  11407. enumerable: true,
  11408. configurable: true
  11409. });
  11410. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11411. get: function () {
  11412. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11413. },
  11414. enumerable: true,
  11415. configurable: true
  11416. });
  11417. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11418. get: function () {
  11419. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11420. },
  11421. enumerable: true,
  11422. configurable: true
  11423. });
  11424. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11425. get: function () {
  11426. return this._bias;
  11427. },
  11428. set: function (bias) {
  11429. this._bias = bias;
  11430. },
  11431. enumerable: true,
  11432. configurable: true
  11433. });
  11434. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11435. get: function () {
  11436. return this._blurBoxOffset;
  11437. },
  11438. set: function (value) {
  11439. var _this = this;
  11440. if (this._blurBoxOffset === value) {
  11441. return;
  11442. }
  11443. this._blurBoxOffset = value;
  11444. if (this._boxBlurPostprocess) {
  11445. this._boxBlurPostprocess.dispose();
  11446. }
  11447. 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);
  11448. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11449. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11450. });
  11451. },
  11452. enumerable: true,
  11453. configurable: true
  11454. });
  11455. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11456. get: function () {
  11457. return this._filter;
  11458. },
  11459. set: function (value) {
  11460. if (this._filter === value) {
  11461. return;
  11462. }
  11463. this._filter = value;
  11464. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11465. this._shadowMap.anisotropicFilteringLevel = 16;
  11466. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11467. }
  11468. else {
  11469. this._shadowMap.anisotropicFilteringLevel = 1;
  11470. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11471. }
  11472. },
  11473. enumerable: true,
  11474. configurable: true
  11475. });
  11476. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11477. get: function () {
  11478. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11479. },
  11480. set: function (value) {
  11481. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11482. },
  11483. enumerable: true,
  11484. configurable: true
  11485. });
  11486. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11487. get: function () {
  11488. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11489. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11490. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11491. },
  11492. set: function (value) {
  11493. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11494. },
  11495. enumerable: true,
  11496. configurable: true
  11497. });
  11498. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11499. get: function () {
  11500. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11501. },
  11502. set: function (value) {
  11503. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11504. },
  11505. enumerable: true,
  11506. configurable: true
  11507. });
  11508. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11509. var defines = [];
  11510. if (this._useFullFloat) {
  11511. defines.push("#define FULLFLOAT");
  11512. }
  11513. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11514. defines.push("#define VSM");
  11515. }
  11516. if (this.getLight().needCube()) {
  11517. defines.push("#define CUBEMAP");
  11518. }
  11519. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11520. var mesh = subMesh.getMesh();
  11521. var material = subMesh.getMaterial();
  11522. // Alpha test
  11523. if (material && material.needAlphaTesting()) {
  11524. defines.push("#define ALPHATEST");
  11525. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11526. attribs.push(BABYLON.VertexBuffer.UVKind);
  11527. defines.push("#define UV1");
  11528. }
  11529. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11530. var alphaTexture = material.getAlphaTestTexture();
  11531. if (alphaTexture.coordinatesIndex === 1) {
  11532. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11533. defines.push("#define UV2");
  11534. }
  11535. }
  11536. }
  11537. // Bones
  11538. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11539. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11540. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11541. if (mesh.numBoneInfluencers > 4) {
  11542. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11543. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11544. }
  11545. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11546. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11547. }
  11548. else {
  11549. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11550. }
  11551. // Instances
  11552. if (useInstances) {
  11553. defines.push("#define INSTANCES");
  11554. attribs.push("world0");
  11555. attribs.push("world1");
  11556. attribs.push("world2");
  11557. attribs.push("world3");
  11558. }
  11559. // Get correct effect
  11560. var join = defines.join("\n");
  11561. if (this._cachedDefines !== join) {
  11562. this._cachedDefines = join;
  11563. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11564. }
  11565. return this._effect.isReady();
  11566. };
  11567. ShadowGenerator.prototype.getShadowMap = function () {
  11568. return this._shadowMap;
  11569. };
  11570. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11571. if (this._shadowMap2) {
  11572. return this._shadowMap2;
  11573. }
  11574. return this._shadowMap;
  11575. };
  11576. ShadowGenerator.prototype.getLight = function () {
  11577. return this._light;
  11578. };
  11579. // Methods
  11580. ShadowGenerator.prototype.getTransformMatrix = function () {
  11581. var scene = this._scene;
  11582. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11583. return this._transformMatrix;
  11584. }
  11585. this._currentRenderID = scene.getRenderId();
  11586. this._currentFaceIndexCache = this._currentFaceIndex;
  11587. var lightPosition = this._light.position;
  11588. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11589. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11590. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11591. }
  11592. if (this._light.computeTransformedPosition()) {
  11593. lightPosition = this._light.transformedPosition;
  11594. }
  11595. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11596. this._cachedPosition = lightPosition.clone();
  11597. this._cachedDirection = this._lightDirection.clone();
  11598. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11599. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11600. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11601. }
  11602. return this._transformMatrix;
  11603. };
  11604. ShadowGenerator.prototype.getDarkness = function () {
  11605. return this._darkness;
  11606. };
  11607. ShadowGenerator.prototype.setDarkness = function (darkness) {
  11608. if (darkness >= 1.0)
  11609. this._darkness = 1.0;
  11610. else if (darkness <= 0.0)
  11611. this._darkness = 0.0;
  11612. else
  11613. this._darkness = darkness;
  11614. };
  11615. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  11616. this._transparencyShadow = hasShadow;
  11617. };
  11618. ShadowGenerator.prototype._packHalf = function (depth) {
  11619. var scale = depth * 255.0;
  11620. var fract = scale - Math.floor(scale);
  11621. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  11622. };
  11623. ShadowGenerator.prototype.dispose = function () {
  11624. this._shadowMap.dispose();
  11625. if (this._shadowMap2) {
  11626. this._shadowMap2.dispose();
  11627. }
  11628. if (this._downSamplePostprocess) {
  11629. this._downSamplePostprocess.dispose();
  11630. }
  11631. if (this._boxBlurPostprocess) {
  11632. this._boxBlurPostprocess.dispose();
  11633. }
  11634. };
  11635. ShadowGenerator.prototype.serialize = function () {
  11636. var serializationObject = {};
  11637. serializationObject.lightId = this._light.id;
  11638. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  11639. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  11640. serializationObject.usePoissonSampling = this.usePoissonSampling;
  11641. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  11642. serializationObject.renderList = [];
  11643. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  11644. var mesh = this.getShadowMap().renderList[meshIndex];
  11645. serializationObject.renderList.push(mesh.id);
  11646. }
  11647. return serializationObject;
  11648. };
  11649. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  11650. //casting to point light, as light is missing the position attr and typescript complains.
  11651. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  11652. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  11653. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  11654. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  11655. meshes.forEach(function (mesh) {
  11656. shadowGenerator.getShadowMap().renderList.push(mesh);
  11657. });
  11658. }
  11659. if (parsedShadowGenerator.usePoissonSampling) {
  11660. shadowGenerator.usePoissonSampling = true;
  11661. }
  11662. else if (parsedShadowGenerator.useVarianceShadowMap) {
  11663. shadowGenerator.useVarianceShadowMap = true;
  11664. }
  11665. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  11666. shadowGenerator.useBlurVarianceShadowMap = true;
  11667. if (parsedShadowGenerator.blurScale) {
  11668. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  11669. }
  11670. if (parsedShadowGenerator.blurBoxOffset) {
  11671. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  11672. }
  11673. }
  11674. if (parsedShadowGenerator.bias !== undefined) {
  11675. shadowGenerator.bias = parsedShadowGenerator.bias;
  11676. }
  11677. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  11678. return shadowGenerator;
  11679. };
  11680. ShadowGenerator._FILTER_NONE = 0;
  11681. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  11682. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  11683. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  11684. return ShadowGenerator;
  11685. }());
  11686. BABYLON.ShadowGenerator = ShadowGenerator;
  11687. })(BABYLON || (BABYLON = {}));
  11688. var BABYLON;
  11689. (function (BABYLON) {
  11690. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  11691. if (boxMin.x > sphereCenter.x + sphereRadius)
  11692. return false;
  11693. if (sphereCenter.x - sphereRadius > boxMax.x)
  11694. return false;
  11695. if (boxMin.y > sphereCenter.y + sphereRadius)
  11696. return false;
  11697. if (sphereCenter.y - sphereRadius > boxMax.y)
  11698. return false;
  11699. if (boxMin.z > sphereCenter.z + sphereRadius)
  11700. return false;
  11701. if (sphereCenter.z - sphereRadius > boxMax.z)
  11702. return false;
  11703. return true;
  11704. };
  11705. var getLowestRoot = (function () {
  11706. var result = { root: 0, found: false };
  11707. return function (a, b, c, maxR) {
  11708. result.root = 0;
  11709. result.found = false;
  11710. var determinant = b * b - 4.0 * a * c;
  11711. if (determinant < 0)
  11712. return result;
  11713. var sqrtD = Math.sqrt(determinant);
  11714. var r1 = (-b - sqrtD) / (2.0 * a);
  11715. var r2 = (-b + sqrtD) / (2.0 * a);
  11716. if (r1 > r2) {
  11717. var temp = r2;
  11718. r2 = r1;
  11719. r1 = temp;
  11720. }
  11721. if (r1 > 0 && r1 < maxR) {
  11722. result.root = r1;
  11723. result.found = true;
  11724. return result;
  11725. }
  11726. if (r2 > 0 && r2 < maxR) {
  11727. result.root = r2;
  11728. result.found = true;
  11729. return result;
  11730. }
  11731. return result;
  11732. };
  11733. })();
  11734. var Collider = (function () {
  11735. function Collider() {
  11736. this.radius = new BABYLON.Vector3(1, 1, 1);
  11737. this.retry = 0;
  11738. this.basePointWorld = BABYLON.Vector3.Zero();
  11739. this.velocityWorld = BABYLON.Vector3.Zero();
  11740. this.normalizedVelocity = BABYLON.Vector3.Zero();
  11741. this._collisionPoint = BABYLON.Vector3.Zero();
  11742. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  11743. this._tempVector = BABYLON.Vector3.Zero();
  11744. this._tempVector2 = BABYLON.Vector3.Zero();
  11745. this._tempVector3 = BABYLON.Vector3.Zero();
  11746. this._tempVector4 = BABYLON.Vector3.Zero();
  11747. this._edge = BABYLON.Vector3.Zero();
  11748. this._baseToVertex = BABYLON.Vector3.Zero();
  11749. this._destinationPoint = BABYLON.Vector3.Zero();
  11750. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  11751. this._displacementVector = BABYLON.Vector3.Zero();
  11752. }
  11753. // Methods
  11754. Collider.prototype._initialize = function (source, dir, e) {
  11755. this.velocity = dir;
  11756. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  11757. this.basePoint = source;
  11758. source.multiplyToRef(this.radius, this.basePointWorld);
  11759. dir.multiplyToRef(this.radius, this.velocityWorld);
  11760. this.velocityWorldLength = this.velocityWorld.length();
  11761. this.epsilon = e;
  11762. this.collisionFound = false;
  11763. };
  11764. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  11765. pa.subtractToRef(point, this._tempVector);
  11766. pb.subtractToRef(point, this._tempVector2);
  11767. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  11768. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11769. if (d < 0)
  11770. return false;
  11771. pc.subtractToRef(point, this._tempVector3);
  11772. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  11773. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11774. if (d < 0)
  11775. return false;
  11776. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  11777. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  11778. return d >= 0;
  11779. };
  11780. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  11781. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  11782. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  11783. if (distance > this.velocityWorldLength + max + sphereRadius) {
  11784. return false;
  11785. }
  11786. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  11787. return false;
  11788. return true;
  11789. };
  11790. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  11791. var t0;
  11792. var embeddedInPlane = false;
  11793. //defensive programming, actually not needed.
  11794. if (!trianglePlaneArray) {
  11795. trianglePlaneArray = [];
  11796. }
  11797. if (!trianglePlaneArray[faceIndex]) {
  11798. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  11799. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  11800. }
  11801. var trianglePlane = trianglePlaneArray[faceIndex];
  11802. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  11803. return;
  11804. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  11805. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  11806. if (normalDotVelocity == 0) {
  11807. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  11808. return;
  11809. embeddedInPlane = true;
  11810. t0 = 0;
  11811. }
  11812. else {
  11813. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11814. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  11815. if (t0 > t1) {
  11816. var temp = t1;
  11817. t1 = t0;
  11818. t0 = temp;
  11819. }
  11820. if (t0 > 1.0 || t1 < 0.0)
  11821. return;
  11822. if (t0 < 0)
  11823. t0 = 0;
  11824. if (t0 > 1.0)
  11825. t0 = 1.0;
  11826. }
  11827. this._collisionPoint.copyFromFloats(0, 0, 0);
  11828. var found = false;
  11829. var t = 1.0;
  11830. if (!embeddedInPlane) {
  11831. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  11832. this.velocity.scaleToRef(t0, this._tempVector);
  11833. this._planeIntersectionPoint.addInPlace(this._tempVector);
  11834. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  11835. found = true;
  11836. t = t0;
  11837. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  11838. }
  11839. }
  11840. if (!found) {
  11841. var velocitySquaredLength = this.velocity.lengthSquared();
  11842. var a = velocitySquaredLength;
  11843. this.basePoint.subtractToRef(p1, this._tempVector);
  11844. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11845. var c = this._tempVector.lengthSquared() - 1.0;
  11846. var lowestRoot = getLowestRoot(a, b, c, t);
  11847. if (lowestRoot.found) {
  11848. t = lowestRoot.root;
  11849. found = true;
  11850. this._collisionPoint.copyFrom(p1);
  11851. }
  11852. this.basePoint.subtractToRef(p2, this._tempVector);
  11853. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11854. c = this._tempVector.lengthSquared() - 1.0;
  11855. lowestRoot = getLowestRoot(a, b, c, t);
  11856. if (lowestRoot.found) {
  11857. t = lowestRoot.root;
  11858. found = true;
  11859. this._collisionPoint.copyFrom(p2);
  11860. }
  11861. this.basePoint.subtractToRef(p3, this._tempVector);
  11862. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  11863. c = this._tempVector.lengthSquared() - 1.0;
  11864. lowestRoot = getLowestRoot(a, b, c, t);
  11865. if (lowestRoot.found) {
  11866. t = lowestRoot.root;
  11867. found = true;
  11868. this._collisionPoint.copyFrom(p3);
  11869. }
  11870. p2.subtractToRef(p1, this._edge);
  11871. p1.subtractToRef(this.basePoint, this._baseToVertex);
  11872. var edgeSquaredLength = this._edge.lengthSquared();
  11873. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11874. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11875. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11876. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11877. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11878. lowestRoot = getLowestRoot(a, b, c, t);
  11879. if (lowestRoot.found) {
  11880. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11881. if (f >= 0.0 && f <= 1.0) {
  11882. t = lowestRoot.root;
  11883. found = true;
  11884. this._edge.scaleInPlace(f);
  11885. p1.addToRef(this._edge, this._collisionPoint);
  11886. }
  11887. }
  11888. p3.subtractToRef(p2, this._edge);
  11889. p2.subtractToRef(this.basePoint, this._baseToVertex);
  11890. edgeSquaredLength = this._edge.lengthSquared();
  11891. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11892. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11893. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11894. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11895. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11896. lowestRoot = getLowestRoot(a, b, c, t);
  11897. if (lowestRoot.found) {
  11898. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11899. if (f >= 0.0 && f <= 1.0) {
  11900. t = lowestRoot.root;
  11901. found = true;
  11902. this._edge.scaleInPlace(f);
  11903. p2.addToRef(this._edge, this._collisionPoint);
  11904. }
  11905. }
  11906. p1.subtractToRef(p3, this._edge);
  11907. p3.subtractToRef(this.basePoint, this._baseToVertex);
  11908. edgeSquaredLength = this._edge.lengthSquared();
  11909. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  11910. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  11911. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  11912. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  11913. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  11914. lowestRoot = getLowestRoot(a, b, c, t);
  11915. if (lowestRoot.found) {
  11916. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  11917. if (f >= 0.0 && f <= 1.0) {
  11918. t = lowestRoot.root;
  11919. found = true;
  11920. this._edge.scaleInPlace(f);
  11921. p3.addToRef(this._edge, this._collisionPoint);
  11922. }
  11923. }
  11924. }
  11925. if (found) {
  11926. var distToCollision = t * this.velocity.length();
  11927. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  11928. if (!this.intersectionPoint) {
  11929. this.intersectionPoint = this._collisionPoint.clone();
  11930. }
  11931. else {
  11932. this.intersectionPoint.copyFrom(this._collisionPoint);
  11933. }
  11934. this.nearestDistance = distToCollision;
  11935. this.collisionFound = true;
  11936. }
  11937. }
  11938. };
  11939. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  11940. for (var i = indexStart; i < indexEnd; i += 3) {
  11941. var p1 = pts[indices[i] - decal];
  11942. var p2 = pts[indices[i + 1] - decal];
  11943. var p3 = pts[indices[i + 2] - decal];
  11944. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  11945. }
  11946. };
  11947. Collider.prototype._getResponse = function (pos, vel) {
  11948. pos.addToRef(vel, this._destinationPoint);
  11949. vel.scaleInPlace((this.nearestDistance / vel.length()));
  11950. this.basePoint.addToRef(vel, pos);
  11951. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  11952. this._slidePlaneNormal.normalize();
  11953. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  11954. pos.addInPlace(this._displacementVector);
  11955. this.intersectionPoint.addInPlace(this._displacementVector);
  11956. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  11957. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  11958. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  11959. };
  11960. return Collider;
  11961. }());
  11962. BABYLON.Collider = Collider;
  11963. })(BABYLON || (BABYLON = {}));
  11964. var BABYLON;
  11965. (function (BABYLON) {
  11966. //WebWorker code will be inserted to this variable.
  11967. BABYLON.CollisionWorker = "";
  11968. (function (WorkerTaskType) {
  11969. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  11970. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  11971. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  11972. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  11973. var WorkerTaskType = BABYLON.WorkerTaskType;
  11974. (function (WorkerReplyType) {
  11975. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  11976. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  11977. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  11978. var WorkerReplyType = BABYLON.WorkerReplyType;
  11979. var CollisionCoordinatorWorker = (function () {
  11980. function CollisionCoordinatorWorker() {
  11981. var _this = this;
  11982. this._scaledPosition = BABYLON.Vector3.Zero();
  11983. this._scaledVelocity = BABYLON.Vector3.Zero();
  11984. this.onMeshUpdated = function (mesh) {
  11985. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  11986. };
  11987. this.onGeometryUpdated = function (geometry) {
  11988. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  11989. };
  11990. this._afterRender = function () {
  11991. if (!_this._init)
  11992. return;
  11993. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  11994. return;
  11995. }
  11996. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  11997. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  11998. if (_this._runningUpdated > 4) {
  11999. return;
  12000. }
  12001. ++_this._runningUpdated;
  12002. var payload = {
  12003. updatedMeshes: _this._addUpdateMeshesList,
  12004. updatedGeometries: _this._addUpdateGeometriesList,
  12005. removedGeometries: _this._toRemoveGeometryArray,
  12006. removedMeshes: _this._toRemoveMeshesArray
  12007. };
  12008. var message = {
  12009. payload: payload,
  12010. taskType: WorkerTaskType.UPDATE
  12011. };
  12012. var serializable = [];
  12013. for (var id in payload.updatedGeometries) {
  12014. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12015. //prepare transferables
  12016. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12017. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12018. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12019. }
  12020. }
  12021. _this._worker.postMessage(message, serializable);
  12022. _this._addUpdateMeshesList = {};
  12023. _this._addUpdateGeometriesList = {};
  12024. _this._toRemoveGeometryArray = [];
  12025. _this._toRemoveMeshesArray = [];
  12026. };
  12027. this._onMessageFromWorker = function (e) {
  12028. var returnData = e.data;
  12029. if (returnData.error != WorkerReplyType.SUCCESS) {
  12030. //TODO what errors can be returned from the worker?
  12031. BABYLON.Tools.Warn("error returned from worker!");
  12032. return;
  12033. }
  12034. switch (returnData.taskType) {
  12035. case WorkerTaskType.INIT:
  12036. _this._init = true;
  12037. //Update the worked with ALL of the scene's current state
  12038. _this._scene.meshes.forEach(function (mesh) {
  12039. _this.onMeshAdded(mesh);
  12040. });
  12041. _this._scene.getGeometries().forEach(function (geometry) {
  12042. _this.onGeometryAdded(geometry);
  12043. });
  12044. break;
  12045. case WorkerTaskType.UPDATE:
  12046. _this._runningUpdated--;
  12047. break;
  12048. case WorkerTaskType.COLLIDE:
  12049. _this._runningCollisionTask = false;
  12050. var returnPayload = returnData.payload;
  12051. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12052. return;
  12053. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12054. //cleanup
  12055. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12056. break;
  12057. }
  12058. };
  12059. this._collisionsCallbackArray = [];
  12060. this._init = false;
  12061. this._runningUpdated = 0;
  12062. this._runningCollisionTask = false;
  12063. this._addUpdateMeshesList = {};
  12064. this._addUpdateGeometriesList = {};
  12065. this._toRemoveGeometryArray = [];
  12066. this._toRemoveMeshesArray = [];
  12067. }
  12068. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12069. if (!this._init)
  12070. return;
  12071. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12072. return;
  12073. position.divideToRef(collider.radius, this._scaledPosition);
  12074. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12075. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12076. var payload = {
  12077. collider: {
  12078. position: this._scaledPosition.asArray(),
  12079. velocity: this._scaledVelocity.asArray(),
  12080. radius: collider.radius.asArray()
  12081. },
  12082. collisionId: collisionIndex,
  12083. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12084. maximumRetry: maximumRetry
  12085. };
  12086. var message = {
  12087. payload: payload,
  12088. taskType: WorkerTaskType.COLLIDE
  12089. };
  12090. this._worker.postMessage(message);
  12091. };
  12092. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12093. this._scene = scene;
  12094. this._scene.registerAfterRender(this._afterRender);
  12095. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12096. this._worker = new Worker(workerUrl);
  12097. this._worker.onmessage = this._onMessageFromWorker;
  12098. var message = {
  12099. payload: {},
  12100. taskType: WorkerTaskType.INIT
  12101. };
  12102. this._worker.postMessage(message);
  12103. };
  12104. CollisionCoordinatorWorker.prototype.destroy = function () {
  12105. this._scene.unregisterAfterRender(this._afterRender);
  12106. this._worker.terminate();
  12107. };
  12108. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12109. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12110. this.onMeshUpdated(mesh);
  12111. };
  12112. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12113. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12114. };
  12115. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12116. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12117. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12118. this.onGeometryUpdated(geometry);
  12119. };
  12120. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12121. this._toRemoveGeometryArray.push(geometry.id);
  12122. };
  12123. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12124. var submeshes = [];
  12125. if (mesh.subMeshes) {
  12126. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12127. return {
  12128. position: idx,
  12129. verticesStart: sm.verticesStart,
  12130. verticesCount: sm.verticesCount,
  12131. indexStart: sm.indexStart,
  12132. indexCount: sm.indexCount,
  12133. hasMaterial: !!sm.getMaterial(),
  12134. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12135. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12136. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12137. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12138. };
  12139. });
  12140. }
  12141. var geometryId = null;
  12142. if (mesh instanceof BABYLON.Mesh) {
  12143. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12144. }
  12145. else if (mesh instanceof BABYLON.InstancedMesh) {
  12146. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12147. }
  12148. return {
  12149. uniqueId: mesh.uniqueId,
  12150. id: mesh.id,
  12151. name: mesh.name,
  12152. geometryId: geometryId,
  12153. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12154. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12155. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12156. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12157. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12158. subMeshes: submeshes,
  12159. checkCollisions: mesh.checkCollisions
  12160. };
  12161. };
  12162. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12163. return {
  12164. id: geometry.id,
  12165. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12166. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12167. indices: new Int32Array(geometry.getIndices() || []),
  12168. };
  12169. };
  12170. return CollisionCoordinatorWorker;
  12171. }());
  12172. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12173. var CollisionCoordinatorLegacy = (function () {
  12174. function CollisionCoordinatorLegacy() {
  12175. this._scaledPosition = BABYLON.Vector3.Zero();
  12176. this._scaledVelocity = BABYLON.Vector3.Zero();
  12177. this._finalPosition = BABYLON.Vector3.Zero();
  12178. }
  12179. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12180. position.divideToRef(collider.radius, this._scaledPosition);
  12181. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12182. collider.collidedMesh = null;
  12183. collider.retry = 0;
  12184. collider.initialVelocity = this._scaledVelocity;
  12185. collider.initialPosition = this._scaledPosition;
  12186. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12187. this._finalPosition.multiplyInPlace(collider.radius);
  12188. //run the callback
  12189. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12190. };
  12191. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12192. this._scene = scene;
  12193. };
  12194. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12195. //Legacy need no destruction method.
  12196. };
  12197. //No update in legacy mode
  12198. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12199. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12200. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12201. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12202. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12203. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12204. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12205. if (excludedMesh === void 0) { excludedMesh = null; }
  12206. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12207. if (collider.retry >= maximumRetry) {
  12208. finalPosition.copyFrom(position);
  12209. return;
  12210. }
  12211. collider._initialize(position, velocity, closeDistance);
  12212. // Check all meshes
  12213. for (var index = 0; index < this._scene.meshes.length; index++) {
  12214. var mesh = this._scene.meshes[index];
  12215. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12216. mesh._checkCollision(collider);
  12217. }
  12218. }
  12219. if (!collider.collisionFound) {
  12220. position.addToRef(velocity, finalPosition);
  12221. return;
  12222. }
  12223. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12224. collider._getResponse(position, velocity);
  12225. }
  12226. if (velocity.length() <= closeDistance) {
  12227. finalPosition.copyFrom(position);
  12228. return;
  12229. }
  12230. collider.retry++;
  12231. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12232. };
  12233. return CollisionCoordinatorLegacy;
  12234. }());
  12235. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12236. })(BABYLON || (BABYLON = {}));
  12237. var BABYLON;
  12238. (function (BABYLON) {
  12239. var Camera = (function (_super) {
  12240. __extends(Camera, _super);
  12241. function Camera(name, position, scene) {
  12242. _super.call(this, name, scene);
  12243. this.upVector = BABYLON.Vector3.Up();
  12244. this.orthoLeft = null;
  12245. this.orthoRight = null;
  12246. this.orthoBottom = null;
  12247. this.orthoTop = null;
  12248. this.fov = 0.8;
  12249. this.minZ = 1.0;
  12250. this.maxZ = 10000.0;
  12251. this.inertia = 0.9;
  12252. this.mode = Camera.PERSPECTIVE_CAMERA;
  12253. this.isIntermediate = false;
  12254. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12255. this.layerMask = 0x0FFFFFFF;
  12256. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12257. // Camera rig members
  12258. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12259. this._rigCameras = new Array();
  12260. // Cache
  12261. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12262. this._projectionMatrix = new BABYLON.Matrix();
  12263. this._postProcesses = new Array();
  12264. this._transformMatrix = BABYLON.Matrix.Zero();
  12265. this._activeMeshes = new BABYLON.SmartArray(256);
  12266. this._globalPosition = BABYLON.Vector3.Zero();
  12267. this._refreshFrustumPlanes = true;
  12268. scene.addCamera(this);
  12269. if (!scene.activeCamera) {
  12270. scene.activeCamera = this;
  12271. }
  12272. this.position = position;
  12273. }
  12274. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12275. get: function () {
  12276. return Camera._PERSPECTIVE_CAMERA;
  12277. },
  12278. enumerable: true,
  12279. configurable: true
  12280. });
  12281. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12282. get: function () {
  12283. return Camera._ORTHOGRAPHIC_CAMERA;
  12284. },
  12285. enumerable: true,
  12286. configurable: true
  12287. });
  12288. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12289. get: function () {
  12290. return Camera._FOVMODE_VERTICAL_FIXED;
  12291. },
  12292. enumerable: true,
  12293. configurable: true
  12294. });
  12295. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12296. get: function () {
  12297. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12298. },
  12299. enumerable: true,
  12300. configurable: true
  12301. });
  12302. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12303. get: function () {
  12304. return Camera._RIG_MODE_NONE;
  12305. },
  12306. enumerable: true,
  12307. configurable: true
  12308. });
  12309. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12310. get: function () {
  12311. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12312. },
  12313. enumerable: true,
  12314. configurable: true
  12315. });
  12316. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12317. get: function () {
  12318. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12319. },
  12320. enumerable: true,
  12321. configurable: true
  12322. });
  12323. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12324. get: function () {
  12325. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12326. },
  12327. enumerable: true,
  12328. configurable: true
  12329. });
  12330. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12331. get: function () {
  12332. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12333. },
  12334. enumerable: true,
  12335. configurable: true
  12336. });
  12337. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12338. get: function () {
  12339. return Camera._RIG_MODE_VR;
  12340. },
  12341. enumerable: true,
  12342. configurable: true
  12343. });
  12344. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12345. get: function () {
  12346. return Camera._RIG_MODE_WEBVR;
  12347. },
  12348. enumerable: true,
  12349. configurable: true
  12350. });
  12351. /**
  12352. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12353. */
  12354. Camera.prototype.toString = function (fullDetails) {
  12355. var ret = "Name: " + this.name;
  12356. ret += ", type: " + this.getTypeName();
  12357. if (this.animations) {
  12358. for (var i = 0; i < this.animations.length; i++) {
  12359. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12360. }
  12361. }
  12362. if (fullDetails) {
  12363. }
  12364. return ret;
  12365. };
  12366. Object.defineProperty(Camera.prototype, "globalPosition", {
  12367. get: function () {
  12368. return this._globalPosition;
  12369. },
  12370. enumerable: true,
  12371. configurable: true
  12372. });
  12373. Camera.prototype.getActiveMeshes = function () {
  12374. return this._activeMeshes;
  12375. };
  12376. Camera.prototype.isActiveMesh = function (mesh) {
  12377. return (this._activeMeshes.indexOf(mesh) !== -1);
  12378. };
  12379. //Cache
  12380. Camera.prototype._initCache = function () {
  12381. _super.prototype._initCache.call(this);
  12382. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12383. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12384. this._cache.mode = undefined;
  12385. this._cache.minZ = undefined;
  12386. this._cache.maxZ = undefined;
  12387. this._cache.fov = undefined;
  12388. this._cache.aspectRatio = undefined;
  12389. this._cache.orthoLeft = undefined;
  12390. this._cache.orthoRight = undefined;
  12391. this._cache.orthoBottom = undefined;
  12392. this._cache.orthoTop = undefined;
  12393. this._cache.renderWidth = undefined;
  12394. this._cache.renderHeight = undefined;
  12395. };
  12396. Camera.prototype._updateCache = function (ignoreParentClass) {
  12397. if (!ignoreParentClass) {
  12398. _super.prototype._updateCache.call(this);
  12399. }
  12400. var engine = this.getEngine();
  12401. this._cache.position.copyFrom(this.position);
  12402. this._cache.upVector.copyFrom(this.upVector);
  12403. this._cache.mode = this.mode;
  12404. this._cache.minZ = this.minZ;
  12405. this._cache.maxZ = this.maxZ;
  12406. this._cache.fov = this.fov;
  12407. this._cache.aspectRatio = engine.getAspectRatio(this);
  12408. this._cache.orthoLeft = this.orthoLeft;
  12409. this._cache.orthoRight = this.orthoRight;
  12410. this._cache.orthoBottom = this.orthoBottom;
  12411. this._cache.orthoTop = this.orthoTop;
  12412. this._cache.renderWidth = engine.getRenderWidth();
  12413. this._cache.renderHeight = engine.getRenderHeight();
  12414. };
  12415. Camera.prototype._updateFromScene = function () {
  12416. this.updateCache();
  12417. this.update();
  12418. };
  12419. // Synchronized
  12420. Camera.prototype._isSynchronized = function () {
  12421. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12422. };
  12423. Camera.prototype._isSynchronizedViewMatrix = function () {
  12424. if (!_super.prototype._isSynchronized.call(this))
  12425. return false;
  12426. return this._cache.position.equals(this.position)
  12427. && this._cache.upVector.equals(this.upVector)
  12428. && this.isSynchronizedWithParent();
  12429. };
  12430. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12431. var check = this._cache.mode === this.mode
  12432. && this._cache.minZ === this.minZ
  12433. && this._cache.maxZ === this.maxZ;
  12434. if (!check) {
  12435. return false;
  12436. }
  12437. var engine = this.getEngine();
  12438. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12439. check = this._cache.fov === this.fov
  12440. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12441. }
  12442. else {
  12443. check = this._cache.orthoLeft === this.orthoLeft
  12444. && this._cache.orthoRight === this.orthoRight
  12445. && this._cache.orthoBottom === this.orthoBottom
  12446. && this._cache.orthoTop === this.orthoTop
  12447. && this._cache.renderWidth === engine.getRenderWidth()
  12448. && this._cache.renderHeight === engine.getRenderHeight();
  12449. }
  12450. return check;
  12451. };
  12452. // Controls
  12453. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12454. };
  12455. Camera.prototype.detachControl = function (element) {
  12456. };
  12457. Camera.prototype.update = function () {
  12458. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12459. this._updateRigCameras();
  12460. }
  12461. this._checkInputs();
  12462. };
  12463. Camera.prototype._checkInputs = function () {
  12464. };
  12465. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12466. // invalidate framebuffer
  12467. if (this._postProcesses.length > 0) {
  12468. this._postProcesses[0].markTextureDirty();
  12469. }
  12470. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12471. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12472. var cam = this._rigCameras[i];
  12473. var rigPostProcess = cam._rigPostProcess;
  12474. // for VR rig, there does not have to be a post process
  12475. if (rigPostProcess) {
  12476. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12477. if (isPass) {
  12478. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12479. cam.isIntermediate = this._postProcesses.length === 0;
  12480. }
  12481. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12482. rigPostProcess.markTextureDirty();
  12483. }
  12484. else {
  12485. cam._postProcesses = this._postProcesses.slice(0);
  12486. }
  12487. }
  12488. };
  12489. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12490. if (insertAt === void 0) { insertAt = null; }
  12491. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12492. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12493. return 0;
  12494. }
  12495. if (insertAt == null || insertAt < 0) {
  12496. this._postProcesses.push(postProcess);
  12497. }
  12498. else {
  12499. this._postProcesses.splice(insertAt, 0, postProcess);
  12500. }
  12501. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12502. return this._postProcesses.indexOf(postProcess);
  12503. };
  12504. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12505. if (atIndices === void 0) { atIndices = null; }
  12506. var result = [];
  12507. var i;
  12508. var index;
  12509. if (!atIndices) {
  12510. var idx = this._postProcesses.indexOf(postProcess);
  12511. if (idx !== -1) {
  12512. this._postProcesses.splice(idx, 1);
  12513. }
  12514. }
  12515. else {
  12516. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12517. // iterate descending, so can just splice as we go
  12518. for (i = atIndices.length - 1; i >= 0; i--) {
  12519. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12520. result.push(i);
  12521. continue;
  12522. }
  12523. this._postProcesses.splice(index, 1);
  12524. }
  12525. }
  12526. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12527. return result;
  12528. };
  12529. Camera.prototype.getWorldMatrix = function () {
  12530. if (!this._worldMatrix) {
  12531. this._worldMatrix = BABYLON.Matrix.Identity();
  12532. }
  12533. var viewMatrix = this.getViewMatrix();
  12534. viewMatrix.invertToRef(this._worldMatrix);
  12535. return this._worldMatrix;
  12536. };
  12537. Camera.prototype._getViewMatrix = function () {
  12538. return BABYLON.Matrix.Identity();
  12539. };
  12540. Camera.prototype.getViewMatrix = function (force) {
  12541. this._computedViewMatrix = this._computeViewMatrix(force);
  12542. if (!force && this._isSynchronizedViewMatrix()) {
  12543. return this._computedViewMatrix;
  12544. }
  12545. this._refreshFrustumPlanes = true;
  12546. if (!this.parent || !this.parent.getWorldMatrix) {
  12547. this._globalPosition.copyFrom(this.position);
  12548. }
  12549. else {
  12550. if (!this._worldMatrix) {
  12551. this._worldMatrix = BABYLON.Matrix.Identity();
  12552. }
  12553. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12554. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12555. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12556. this._computedViewMatrix.invert();
  12557. this._markSyncedWithParent();
  12558. }
  12559. this._currentRenderId = this.getScene().getRenderId();
  12560. return this._computedViewMatrix;
  12561. };
  12562. Camera.prototype._computeViewMatrix = function (force) {
  12563. if (!force && this._isSynchronizedViewMatrix()) {
  12564. return this._computedViewMatrix;
  12565. }
  12566. this._computedViewMatrix = this._getViewMatrix();
  12567. this._currentRenderId = this.getScene().getRenderId();
  12568. return this._computedViewMatrix;
  12569. };
  12570. Camera.prototype.getProjectionMatrix = function (force) {
  12571. if (!force && this._isSynchronizedProjectionMatrix()) {
  12572. return this._projectionMatrix;
  12573. }
  12574. this._refreshFrustumPlanes = true;
  12575. var engine = this.getEngine();
  12576. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12577. if (this.minZ <= 0) {
  12578. this.minZ = 0.1;
  12579. }
  12580. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12581. return this._projectionMatrix;
  12582. }
  12583. var halfWidth = engine.getRenderWidth() / 2.0;
  12584. var halfHeight = engine.getRenderHeight() / 2.0;
  12585. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  12586. return this._projectionMatrix;
  12587. };
  12588. Camera.prototype.getTranformationMatrix = function () {
  12589. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12590. return this._transformMatrix;
  12591. };
  12592. Camera.prototype.updateFrustumPlanes = function () {
  12593. if (!this._refreshFrustumPlanes) {
  12594. return;
  12595. }
  12596. this.getTranformationMatrix();
  12597. if (!this._frustumPlanes) {
  12598. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12599. }
  12600. else {
  12601. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12602. }
  12603. this._refreshFrustumPlanes = false;
  12604. };
  12605. Camera.prototype.isInFrustum = function (target) {
  12606. this.updateFrustumPlanes();
  12607. return target.isInFrustum(this._frustumPlanes);
  12608. };
  12609. Camera.prototype.isCompletelyInFrustum = function (target) {
  12610. this.updateFrustumPlanes();
  12611. return target.isCompletelyInFrustum(this._frustumPlanes);
  12612. };
  12613. Camera.prototype.dispose = function () {
  12614. // Animations
  12615. this.getScene().stopAnimation(this);
  12616. // Remove from scene
  12617. this.getScene().removeCamera(this);
  12618. while (this._rigCameras.length > 0) {
  12619. this._rigCameras.pop().dispose();
  12620. }
  12621. // Postprocesses
  12622. for (var i = 0; i < this._postProcesses.length; ++i) {
  12623. this._postProcesses[i].dispose(this);
  12624. }
  12625. _super.prototype.dispose.call(this);
  12626. };
  12627. // ---- Camera rigs section ----
  12628. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  12629. while (this._rigCameras.length > 0) {
  12630. this._rigCameras.pop().dispose();
  12631. }
  12632. this.cameraRigMode = mode;
  12633. this._cameraRigParams = {};
  12634. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  12635. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  12636. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  12637. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  12638. // create the rig cameras, unless none
  12639. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12640. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  12641. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  12642. }
  12643. switch (this.cameraRigMode) {
  12644. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  12645. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12646. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  12647. break;
  12648. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  12649. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  12650. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  12651. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12652. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  12653. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  12654. break;
  12655. case Camera.RIG_MODE_VR:
  12656. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  12657. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  12658. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12659. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12660. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  12661. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  12662. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  12663. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  12664. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12665. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12666. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  12667. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  12668. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  12669. if (metrics.compensateDistortion) {
  12670. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  12671. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  12672. }
  12673. break;
  12674. case Camera.RIG_MODE_WEBVR:
  12675. if (rigParams.vrDisplay) {
  12676. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  12677. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  12678. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  12679. this._rigCameras[0].setCameraRigParameter("vrFieldOfView", leftEye.fieldOfView);
  12680. this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  12681. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12682. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  12683. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  12684. this._rigCameras[1].setCameraRigParameter("vrFieldOfView", rightEye.fieldOfView);
  12685. this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", BABYLON.Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  12686. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  12687. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  12688. }
  12689. break;
  12690. }
  12691. this._cascadePostProcessesToRigCams();
  12692. this.
  12693. update();
  12694. };
  12695. Camera.prototype._getVRProjectionMatrix = function () {
  12696. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12697. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  12698. return this._projectionMatrix;
  12699. };
  12700. Camera.prototype._getWebVRProjectionMatrix = function () {
  12701. BABYLON.Matrix.PerspectiveFovWebVRToRef(this._cameraRigParams['vrFieldOfView'], this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  12702. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams['vrOffsetMatrix'], this._projectionMatrix);
  12703. return this._projectionMatrix;
  12704. };
  12705. Camera.prototype.setCameraRigParameter = function (name, value) {
  12706. if (!this._cameraRigParams) {
  12707. this._cameraRigParams = {};
  12708. }
  12709. this._cameraRigParams[name] = value;
  12710. //provisionnally:
  12711. if (name === "interaxialDistance") {
  12712. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  12713. }
  12714. };
  12715. /**
  12716. * needs to be overridden by children so sub has required properties to be copied
  12717. */
  12718. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  12719. return null;
  12720. };
  12721. /**
  12722. * May need to be overridden by children
  12723. */
  12724. Camera.prototype._updateRigCameras = function () {
  12725. for (var i = 0; i < this._rigCameras.length; i++) {
  12726. this._rigCameras[i].minZ = this.minZ;
  12727. this._rigCameras[i].maxZ = this.maxZ;
  12728. this._rigCameras[i].fov = this.fov;
  12729. }
  12730. // only update viewport when ANAGLYPH
  12731. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  12732. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  12733. }
  12734. };
  12735. Camera.prototype._setupInputs = function () {
  12736. };
  12737. Camera.prototype.serialize = function () {
  12738. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12739. // Type
  12740. serializationObject.type = this.getTypeName();
  12741. // Parent
  12742. if (this.parent) {
  12743. serializationObject.parentId = this.parent.id;
  12744. }
  12745. if (this.inputs) {
  12746. this.inputs.serialize(serializationObject);
  12747. }
  12748. // Animations
  12749. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12750. serializationObject.ranges = this.serializeAnimationRanges();
  12751. return serializationObject;
  12752. };
  12753. Camera.prototype.getTypeName = function () {
  12754. return "Camera";
  12755. };
  12756. Camera.prototype.clone = function (name) {
  12757. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  12758. };
  12759. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  12760. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  12761. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  12762. switch (type) {
  12763. case "ArcRotateCamera":
  12764. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  12765. case "DeviceOrientationCamera":
  12766. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  12767. case "FollowCamera":
  12768. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  12769. case "ArcFollowCamera":
  12770. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  12771. case "GamepadCamera":
  12772. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  12773. case "TouchCamera":
  12774. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  12775. case "VirtualJoysticksCamera":
  12776. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  12777. case "WebVRFreeCamera":
  12778. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12779. case "VRDeviceOrientationFreeCamera":
  12780. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  12781. case "AnaglyphArcRotateCamera":
  12782. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12783. case "AnaglyphFreeCamera":
  12784. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12785. case "AnaglyphGamepadCamera":
  12786. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12787. case "AnaglyphUniversalCamera":
  12788. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  12789. case "StereoscopicArcRotateCamera":
  12790. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12791. case "StereoscopicFreeCamera":
  12792. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12793. case "StereoscopicGamepadCamera":
  12794. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12795. case "StereoscopicUniversalCamera":
  12796. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  12797. case "FreeCamera":
  12798. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12799. default:
  12800. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  12801. }
  12802. };
  12803. Camera.Parse = function (parsedCamera, scene) {
  12804. var type = parsedCamera.type;
  12805. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  12806. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  12807. // Parent
  12808. if (parsedCamera.parentId) {
  12809. camera._waitingParentId = parsedCamera.parentId;
  12810. }
  12811. //If camera has an input manager, let it parse inputs settings
  12812. if (camera.inputs) {
  12813. camera.inputs.parse(parsedCamera);
  12814. camera._setupInputs();
  12815. }
  12816. // Target
  12817. if (parsedCamera.target) {
  12818. if (camera.setTarget) {
  12819. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  12820. }
  12821. }
  12822. // Apply 3d rig, when found
  12823. if (parsedCamera.cameraRigMode) {
  12824. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  12825. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  12826. }
  12827. // Animations
  12828. if (parsedCamera.animations) {
  12829. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  12830. var parsedAnimation = parsedCamera.animations[animationIndex];
  12831. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12832. }
  12833. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  12834. }
  12835. if (parsedCamera.autoAnimate) {
  12836. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  12837. }
  12838. return camera;
  12839. };
  12840. // Statics
  12841. Camera._PERSPECTIVE_CAMERA = 0;
  12842. Camera._ORTHOGRAPHIC_CAMERA = 1;
  12843. Camera._FOVMODE_VERTICAL_FIXED = 0;
  12844. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  12845. Camera._RIG_MODE_NONE = 0;
  12846. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  12847. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  12848. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  12849. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  12850. Camera._RIG_MODE_VR = 20;
  12851. Camera._RIG_MODE_WEBVR = 21;
  12852. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  12853. __decorate([
  12854. BABYLON.serializeAsVector3()
  12855. ], Camera.prototype, "position", void 0);
  12856. __decorate([
  12857. BABYLON.serializeAsVector3()
  12858. ], Camera.prototype, "upVector", void 0);
  12859. __decorate([
  12860. BABYLON.serialize()
  12861. ], Camera.prototype, "orthoLeft", void 0);
  12862. __decorate([
  12863. BABYLON.serialize()
  12864. ], Camera.prototype, "orthoRight", void 0);
  12865. __decorate([
  12866. BABYLON.serialize()
  12867. ], Camera.prototype, "orthoBottom", void 0);
  12868. __decorate([
  12869. BABYLON.serialize()
  12870. ], Camera.prototype, "orthoTop", void 0);
  12871. __decorate([
  12872. BABYLON.serialize()
  12873. ], Camera.prototype, "fov", void 0);
  12874. __decorate([
  12875. BABYLON.serialize()
  12876. ], Camera.prototype, "minZ", void 0);
  12877. __decorate([
  12878. BABYLON.serialize()
  12879. ], Camera.prototype, "maxZ", void 0);
  12880. __decorate([
  12881. BABYLON.serialize()
  12882. ], Camera.prototype, "inertia", void 0);
  12883. __decorate([
  12884. BABYLON.serialize()
  12885. ], Camera.prototype, "mode", void 0);
  12886. __decorate([
  12887. BABYLON.serialize()
  12888. ], Camera.prototype, "layerMask", void 0);
  12889. __decorate([
  12890. BABYLON.serialize()
  12891. ], Camera.prototype, "fovMode", void 0);
  12892. __decorate([
  12893. BABYLON.serialize()
  12894. ], Camera.prototype, "cameraRigMode", void 0);
  12895. __decorate([
  12896. BABYLON.serialize()
  12897. ], Camera.prototype, "interaxialDistance", void 0);
  12898. __decorate([
  12899. BABYLON.serialize()
  12900. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  12901. return Camera;
  12902. }(BABYLON.Node));
  12903. BABYLON.Camera = Camera;
  12904. })(BABYLON || (BABYLON = {}));
  12905. var BABYLON;
  12906. (function (BABYLON) {
  12907. BABYLON.CameraInputTypes = {};
  12908. var CameraInputsManager = (function () {
  12909. function CameraInputsManager(camera) {
  12910. this.attached = {};
  12911. this.camera = camera;
  12912. this.checkInputs = function () { };
  12913. }
  12914. CameraInputsManager.prototype.add = function (input) {
  12915. var type = input.getSimpleName();
  12916. if (this.attached[type]) {
  12917. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  12918. return;
  12919. }
  12920. this.attached[type] = input;
  12921. input.camera = this.camera;
  12922. //for checkInputs, we are dynamically creating a function
  12923. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  12924. if (input.checkInputs) {
  12925. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12926. }
  12927. if (this.attachedElement) {
  12928. input.attachControl(this.attachedElement);
  12929. }
  12930. };
  12931. CameraInputsManager.prototype.remove = function (inputToRemove) {
  12932. for (var cam in this.attached) {
  12933. var input = this.attached[cam];
  12934. if (input === inputToRemove) {
  12935. input.detachControl(this.attachedElement);
  12936. delete this.attached[cam];
  12937. this.rebuildInputCheck();
  12938. }
  12939. }
  12940. };
  12941. CameraInputsManager.prototype.removeByType = function (inputType) {
  12942. for (var cam in this.attached) {
  12943. var input = this.attached[cam];
  12944. if (input.getTypeName() === inputType) {
  12945. input.detachControl(this.attachedElement);
  12946. delete this.attached[cam];
  12947. this.rebuildInputCheck();
  12948. }
  12949. }
  12950. };
  12951. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  12952. var current = this.checkInputs;
  12953. return function () {
  12954. current();
  12955. fn();
  12956. };
  12957. };
  12958. CameraInputsManager.prototype.attachInput = function (input) {
  12959. input.attachControl(this.attachedElement, this.noPreventDefault);
  12960. };
  12961. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  12962. if (this.attachedElement) {
  12963. return;
  12964. }
  12965. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  12966. this.attachedElement = element;
  12967. this.noPreventDefault = noPreventDefault;
  12968. for (var cam in this.attached) {
  12969. var input = this.attached[cam];
  12970. this.attached[cam].attachControl(element, noPreventDefault);
  12971. }
  12972. };
  12973. CameraInputsManager.prototype.detachElement = function (element) {
  12974. if (this.attachedElement !== element) {
  12975. return;
  12976. }
  12977. for (var cam in this.attached) {
  12978. var input = this.attached[cam];
  12979. this.attached[cam].detachControl(element);
  12980. }
  12981. this.attachedElement = null;
  12982. };
  12983. CameraInputsManager.prototype.rebuildInputCheck = function () {
  12984. this.checkInputs = function () { };
  12985. for (var cam in this.attached) {
  12986. var input = this.attached[cam];
  12987. if (input.checkInputs) {
  12988. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  12989. }
  12990. }
  12991. };
  12992. CameraInputsManager.prototype.clear = function () {
  12993. if (this.attachedElement) {
  12994. this.detachElement(this.attachedElement);
  12995. }
  12996. this.attached = {};
  12997. this.attachedElement = null;
  12998. this.checkInputs = function () { };
  12999. };
  13000. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13001. var inputs = {};
  13002. for (var cam in this.attached) {
  13003. var input = this.attached[cam];
  13004. var res = BABYLON.SerializationHelper.Serialize(input);
  13005. inputs[input.getTypeName()] = res;
  13006. }
  13007. serializedCamera.inputsmgr = inputs;
  13008. };
  13009. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13010. var parsedInputs = parsedCamera.inputsmgr;
  13011. if (parsedInputs) {
  13012. this.clear();
  13013. for (var n in parsedInputs) {
  13014. var construct = BABYLON.CameraInputTypes[n];
  13015. if (construct) {
  13016. var parsedinput = parsedInputs[n];
  13017. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13018. this.add(input);
  13019. }
  13020. }
  13021. }
  13022. else {
  13023. //2016-03-08 this part is for managing backward compatibility
  13024. for (var n in this.attached) {
  13025. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13026. if (construct) {
  13027. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13028. this.remove(this.attached[n]);
  13029. this.add(input);
  13030. }
  13031. }
  13032. }
  13033. };
  13034. return CameraInputsManager;
  13035. }());
  13036. BABYLON.CameraInputsManager = CameraInputsManager;
  13037. })(BABYLON || (BABYLON = {}));
  13038. var BABYLON;
  13039. (function (BABYLON) {
  13040. var FreeCameraMouseInput = (function () {
  13041. function FreeCameraMouseInput(touchEnabled) {
  13042. if (touchEnabled === void 0) { touchEnabled = true; }
  13043. this.touchEnabled = touchEnabled;
  13044. this.angularSensibility = 2000.0;
  13045. }
  13046. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13047. var _this = this;
  13048. if (!this._pointerInput) {
  13049. var camera = this.camera;
  13050. var engine = this.camera.getEngine();
  13051. this._pointerInput = function (p, s) {
  13052. var evt = p.event;
  13053. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13054. return;
  13055. }
  13056. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13057. try {
  13058. evt.srcElement.setPointerCapture(evt.pointerId);
  13059. }
  13060. catch (e) {
  13061. }
  13062. _this.previousPosition = {
  13063. x: evt.clientX,
  13064. y: evt.clientY
  13065. };
  13066. if (!noPreventDefault) {
  13067. evt.preventDefault();
  13068. element.focus();
  13069. }
  13070. }
  13071. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13072. try {
  13073. evt.srcElement.releasePointerCapture(evt.pointerId);
  13074. }
  13075. catch (e) {
  13076. }
  13077. _this.previousPosition = null;
  13078. if (!noPreventDefault) {
  13079. evt.preventDefault();
  13080. }
  13081. }
  13082. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13083. if (!_this.previousPosition && !engine.isPointerLock) {
  13084. return;
  13085. }
  13086. var offsetX;
  13087. var offsetY;
  13088. if (!engine.isPointerLock) {
  13089. offsetX = evt.clientX - _this.previousPosition.x;
  13090. offsetY = evt.clientY - _this.previousPosition.y;
  13091. }
  13092. else {
  13093. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13094. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13095. }
  13096. camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13097. camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13098. _this.previousPosition = {
  13099. x: evt.clientX,
  13100. y: evt.clientY
  13101. };
  13102. if (!noPreventDefault) {
  13103. evt.preventDefault();
  13104. }
  13105. }
  13106. };
  13107. }
  13108. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13109. };
  13110. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13111. if (this._observer && element) {
  13112. this.camera.getScene().onPointerObservable.remove(this._observer);
  13113. this._observer = null;
  13114. this.previousPosition = null;
  13115. }
  13116. };
  13117. FreeCameraMouseInput.prototype.getTypeName = function () {
  13118. return "FreeCameraMouseInput";
  13119. };
  13120. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13121. return "mouse";
  13122. };
  13123. __decorate([
  13124. BABYLON.serialize()
  13125. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13126. return FreeCameraMouseInput;
  13127. }());
  13128. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13129. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13130. })(BABYLON || (BABYLON = {}));
  13131. var BABYLON;
  13132. (function (BABYLON) {
  13133. var FreeCameraKeyboardMoveInput = (function () {
  13134. function FreeCameraKeyboardMoveInput() {
  13135. this._keys = [];
  13136. this.keysUp = [38];
  13137. this.keysDown = [40];
  13138. this.keysLeft = [37];
  13139. this.keysRight = [39];
  13140. }
  13141. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13142. var _this = this;
  13143. if (!this._onKeyDown) {
  13144. element.tabIndex = 1;
  13145. this._onKeyDown = function (evt) {
  13146. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13147. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13148. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13149. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13150. var index = _this._keys.indexOf(evt.keyCode);
  13151. if (index === -1) {
  13152. _this._keys.push(evt.keyCode);
  13153. }
  13154. if (!noPreventDefault) {
  13155. evt.preventDefault();
  13156. }
  13157. }
  13158. };
  13159. this._onKeyUp = function (evt) {
  13160. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13161. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13162. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13163. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13164. var index = _this._keys.indexOf(evt.keyCode);
  13165. if (index >= 0) {
  13166. _this._keys.splice(index, 1);
  13167. }
  13168. if (!noPreventDefault) {
  13169. evt.preventDefault();
  13170. }
  13171. }
  13172. };
  13173. element.addEventListener("keydown", this._onKeyDown, false);
  13174. element.addEventListener("keyup", this._onKeyUp, false);
  13175. BABYLON.Tools.RegisterTopRootEvents([
  13176. { name: "blur", handler: this._onLostFocus }
  13177. ]);
  13178. }
  13179. };
  13180. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13181. if (this._onKeyDown) {
  13182. element.removeEventListener("keydown", this._onKeyDown);
  13183. element.removeEventListener("keyup", this._onKeyUp);
  13184. BABYLON.Tools.UnregisterTopRootEvents([
  13185. { name: "blur", handler: this._onLostFocus }
  13186. ]);
  13187. this._keys = [];
  13188. this._onKeyDown = null;
  13189. this._onKeyUp = null;
  13190. }
  13191. };
  13192. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13193. if (this._onKeyDown) {
  13194. var camera = this.camera;
  13195. // Keyboard
  13196. for (var index = 0; index < this._keys.length; index++) {
  13197. var keyCode = this._keys[index];
  13198. var speed = camera._computeLocalCameraSpeed();
  13199. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13200. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13201. }
  13202. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13203. camera._localDirection.copyFromFloats(0, 0, speed);
  13204. }
  13205. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13206. camera._localDirection.copyFromFloats(speed, 0, 0);
  13207. }
  13208. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13209. camera._localDirection.copyFromFloats(0, 0, -speed);
  13210. }
  13211. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13212. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13213. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13214. }
  13215. }
  13216. };
  13217. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13218. return "FreeCameraKeyboardMoveInput";
  13219. };
  13220. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13221. this._keys = [];
  13222. };
  13223. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13224. return "keyboard";
  13225. };
  13226. __decorate([
  13227. BABYLON.serialize()
  13228. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13229. __decorate([
  13230. BABYLON.serialize()
  13231. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13232. __decorate([
  13233. BABYLON.serialize()
  13234. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13235. __decorate([
  13236. BABYLON.serialize()
  13237. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13238. return FreeCameraKeyboardMoveInput;
  13239. }());
  13240. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13241. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13242. })(BABYLON || (BABYLON = {}));
  13243. var BABYLON;
  13244. (function (BABYLON) {
  13245. var FreeCameraTouchInput = (function () {
  13246. function FreeCameraTouchInput() {
  13247. this._offsetX = null;
  13248. this._offsetY = null;
  13249. this._pointerCount = 0;
  13250. this._pointerPressed = [];
  13251. this.touchAngularSensibility = 200000.0;
  13252. this.touchMoveSensibility = 250.0;
  13253. }
  13254. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13255. var _this = this;
  13256. var previousPosition;
  13257. if (this._pointerInput === undefined) {
  13258. this._onLostFocus = function (evt) {
  13259. _this._offsetX = null;
  13260. _this._offsetY = null;
  13261. };
  13262. this._pointerInput = function (p, s) {
  13263. var evt = p.event;
  13264. if (evt.pointerType === "mouse") {
  13265. return;
  13266. }
  13267. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13268. if (!noPreventDefault) {
  13269. evt.preventDefault();
  13270. }
  13271. _this._pointerPressed.push(evt.pointerId);
  13272. if (_this._pointerPressed.length !== 1) {
  13273. return;
  13274. }
  13275. previousPosition = {
  13276. x: evt.clientX,
  13277. y: evt.clientY
  13278. };
  13279. }
  13280. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13281. if (!noPreventDefault) {
  13282. evt.preventDefault();
  13283. }
  13284. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13285. if (index === -1) {
  13286. return;
  13287. }
  13288. _this._pointerPressed.splice(index, 1);
  13289. if (index != 0) {
  13290. return;
  13291. }
  13292. previousPosition = null;
  13293. _this._offsetX = null;
  13294. _this._offsetY = null;
  13295. }
  13296. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13297. if (!noPreventDefault) {
  13298. evt.preventDefault();
  13299. }
  13300. if (!previousPosition) {
  13301. return;
  13302. }
  13303. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13304. if (index != 0) {
  13305. return;
  13306. }
  13307. _this._offsetX = evt.clientX - previousPosition.x;
  13308. _this._offsetY = -(evt.clientY - previousPosition.y);
  13309. }
  13310. };
  13311. }
  13312. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13313. element.addEventListener("blur", this._onLostFocus);
  13314. };
  13315. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13316. if (this._pointerInput && element) {
  13317. this.camera.getScene().onPointerObservable.remove(this._observer);
  13318. this._observer = null;
  13319. element.removeEventListener("blur", this._onLostFocus);
  13320. this._onLostFocus = null;
  13321. this._pointerPressed = [];
  13322. this._offsetX = null;
  13323. this._offsetY = null;
  13324. this._pointerCount = 0;
  13325. }
  13326. };
  13327. FreeCameraTouchInput.prototype.checkInputs = function () {
  13328. if (this._offsetX) {
  13329. var camera = this.camera;
  13330. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13331. if (this._pointerPressed.length > 1) {
  13332. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13333. }
  13334. else {
  13335. var speed = camera._computeLocalCameraSpeed();
  13336. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13337. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13338. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13339. }
  13340. }
  13341. };
  13342. FreeCameraTouchInput.prototype.getTypeName = function () {
  13343. return "FreeCameraTouchInput";
  13344. };
  13345. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13346. return "touch";
  13347. };
  13348. __decorate([
  13349. BABYLON.serialize()
  13350. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13351. __decorate([
  13352. BABYLON.serialize()
  13353. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13354. return FreeCameraTouchInput;
  13355. }());
  13356. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13357. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13358. })(BABYLON || (BABYLON = {}));
  13359. var BABYLON;
  13360. (function (BABYLON) {
  13361. var FreeCameraDeviceOrientationInput = (function () {
  13362. function FreeCameraDeviceOrientationInput() {
  13363. var _this = this;
  13364. this._screenOrientationAngle = 0;
  13365. this._screenQuaternion = new BABYLON.Quaternion();
  13366. this._alpha = 0;
  13367. this._beta = 0;
  13368. this._gamma = 0;
  13369. this._orientationChanged = function () {
  13370. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13371. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13372. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13373. };
  13374. this._deviceOrientation = function (evt) {
  13375. _this._alpha = evt.alpha;
  13376. _this._beta = evt.beta;
  13377. _this._gamma = evt.gamma;
  13378. };
  13379. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13380. this._orientationChanged();
  13381. }
  13382. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13383. get: function () {
  13384. return this._camera;
  13385. },
  13386. set: function (camera) {
  13387. this._camera = camera;
  13388. if (!this._camera.rotationQuaternion)
  13389. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13390. },
  13391. enumerable: true,
  13392. configurable: true
  13393. });
  13394. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13395. window.addEventListener("orientationchange", this._orientationChanged);
  13396. window.addEventListener("deviceorientation", this._deviceOrientation);
  13397. };
  13398. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13399. window.removeEventListener("orientationchange", this._orientationChanged);
  13400. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13401. };
  13402. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13403. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13404. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13405. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13406. //Mirror on XY Plane
  13407. this._camera.rotationQuaternion.z *= -1;
  13408. this._camera.rotationQuaternion.w *= -1;
  13409. };
  13410. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13411. return "FreeCameraDeviceOrientationInput";
  13412. };
  13413. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13414. return "deviceOrientation";
  13415. };
  13416. return FreeCameraDeviceOrientationInput;
  13417. }());
  13418. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13419. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13420. })(BABYLON || (BABYLON = {}));
  13421. var BABYLON;
  13422. (function (BABYLON) {
  13423. var FreeCameraGamepadInput = (function () {
  13424. function FreeCameraGamepadInput() {
  13425. this.gamepadAngularSensibility = 200;
  13426. this.gamepadMoveSensibility = 40;
  13427. }
  13428. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13429. var _this = this;
  13430. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13431. };
  13432. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13433. if (this._gamepads) {
  13434. this._gamepads.dispose();
  13435. }
  13436. this.gamepad = null;
  13437. };
  13438. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13439. if (this.gamepad) {
  13440. var camera = this.camera;
  13441. var LSValues = this.gamepad.leftStick;
  13442. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13443. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13444. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13445. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13446. var RSValues = this.gamepad.rightStick;
  13447. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13448. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13449. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13450. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13451. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13452. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13453. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13454. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13455. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13456. }
  13457. };
  13458. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13459. // Only the first gamepad can control the camera
  13460. if (gamepad.index === 0) {
  13461. this.gamepad = gamepad;
  13462. }
  13463. };
  13464. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13465. return "FreeCameraGamepadInput";
  13466. };
  13467. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13468. return "gamepad";
  13469. };
  13470. __decorate([
  13471. BABYLON.serialize()
  13472. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13473. __decorate([
  13474. BABYLON.serialize()
  13475. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13476. return FreeCameraGamepadInput;
  13477. }());
  13478. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13479. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13480. })(BABYLON || (BABYLON = {}));
  13481. var BABYLON;
  13482. (function (BABYLON) {
  13483. var ArcRotateCameraKeyboardMoveInput = (function () {
  13484. function ArcRotateCameraKeyboardMoveInput() {
  13485. this._keys = [];
  13486. this.keysUp = [38];
  13487. this.keysDown = [40];
  13488. this.keysLeft = [37];
  13489. this.keysRight = [39];
  13490. }
  13491. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13492. var _this = this;
  13493. element.tabIndex = 1;
  13494. this._onKeyDown = function (evt) {
  13495. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13496. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13497. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13498. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13499. var index = _this._keys.indexOf(evt.keyCode);
  13500. if (index === -1) {
  13501. _this._keys.push(evt.keyCode);
  13502. }
  13503. if (evt.preventDefault) {
  13504. if (!noPreventDefault) {
  13505. evt.preventDefault();
  13506. }
  13507. }
  13508. }
  13509. };
  13510. this._onKeyUp = function (evt) {
  13511. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13512. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13513. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13514. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13515. var index = _this._keys.indexOf(evt.keyCode);
  13516. if (index >= 0) {
  13517. _this._keys.splice(index, 1);
  13518. }
  13519. if (evt.preventDefault) {
  13520. if (!noPreventDefault) {
  13521. evt.preventDefault();
  13522. }
  13523. }
  13524. }
  13525. };
  13526. this._onLostFocus = function () {
  13527. _this._keys = [];
  13528. };
  13529. element.addEventListener("keydown", this._onKeyDown, false);
  13530. element.addEventListener("keyup", this._onKeyUp, false);
  13531. BABYLON.Tools.RegisterTopRootEvents([
  13532. { name: "blur", handler: this._onLostFocus }
  13533. ]);
  13534. };
  13535. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13536. if (element) {
  13537. element.removeEventListener("keydown", this._onKeyDown);
  13538. element.removeEventListener("keyup", this._onKeyUp);
  13539. }
  13540. BABYLON.Tools.UnregisterTopRootEvents([
  13541. { name: "blur", handler: this._onLostFocus }
  13542. ]);
  13543. this._keys = [];
  13544. this._onKeyDown = null;
  13545. this._onKeyUp = null;
  13546. this._onLostFocus = null;
  13547. };
  13548. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13549. if (this._onKeyDown) {
  13550. var camera = this.camera;
  13551. for (var index = 0; index < this._keys.length; index++) {
  13552. var keyCode = this._keys[index];
  13553. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13554. camera.inertialAlphaOffset -= 0.01;
  13555. }
  13556. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13557. camera.inertialBetaOffset -= 0.01;
  13558. }
  13559. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13560. camera.inertialAlphaOffset += 0.01;
  13561. }
  13562. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13563. camera.inertialBetaOffset += 0.01;
  13564. }
  13565. }
  13566. }
  13567. };
  13568. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13569. return "ArcRotateCameraKeyboardMoveInput";
  13570. };
  13571. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13572. return "keyboard";
  13573. };
  13574. __decorate([
  13575. BABYLON.serialize()
  13576. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13577. __decorate([
  13578. BABYLON.serialize()
  13579. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13580. __decorate([
  13581. BABYLON.serialize()
  13582. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13583. __decorate([
  13584. BABYLON.serialize()
  13585. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13586. return ArcRotateCameraKeyboardMoveInput;
  13587. }());
  13588. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  13589. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  13590. })(BABYLON || (BABYLON = {}));
  13591. var BABYLON;
  13592. (function (BABYLON) {
  13593. var ArcRotateCameraMouseWheelInput = (function () {
  13594. function ArcRotateCameraMouseWheelInput() {
  13595. this.wheelPrecision = 3.0;
  13596. }
  13597. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  13598. var _this = this;
  13599. this._wheel = function (p, s) {
  13600. //sanity check - this should be a PointerWheel event.
  13601. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  13602. return;
  13603. var event = p.event;
  13604. var delta = 0;
  13605. if (event.wheelDelta) {
  13606. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  13607. }
  13608. else if (event.detail) {
  13609. delta = -event.detail / _this.wheelPrecision;
  13610. }
  13611. if (delta)
  13612. _this.camera.inertialRadiusOffset += delta;
  13613. if (event.preventDefault) {
  13614. if (!noPreventDefault) {
  13615. event.preventDefault();
  13616. }
  13617. }
  13618. };
  13619. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  13620. };
  13621. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  13622. if (this._observer && element) {
  13623. this.camera.getScene().onPointerObservable.remove(this._observer);
  13624. this._observer = null;
  13625. this._wheel = null;
  13626. }
  13627. };
  13628. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  13629. return "ArcRotateCameraMouseWheelInput";
  13630. };
  13631. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  13632. return "mousewheel";
  13633. };
  13634. __decorate([
  13635. BABYLON.serialize()
  13636. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  13637. return ArcRotateCameraMouseWheelInput;
  13638. }());
  13639. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  13640. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  13641. })(BABYLON || (BABYLON = {}));
  13642. var BABYLON;
  13643. (function (BABYLON) {
  13644. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  13645. var ArcRotateCameraPointersInput = (function () {
  13646. function ArcRotateCameraPointersInput() {
  13647. this.angularSensibilityX = 1000.0;
  13648. this.angularSensibilityY = 1000.0;
  13649. this.pinchPrecision = 6.0;
  13650. this.panningSensibility = 50.0;
  13651. this._isPanClick = false;
  13652. this.pinchInwards = true;
  13653. }
  13654. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  13655. var _this = this;
  13656. var engine = this.camera.getEngine();
  13657. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  13658. var pointA, pointB;
  13659. var previousPinchDistance = 0;
  13660. this._pointerInput = function (p, s) {
  13661. var evt = p.event;
  13662. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13663. try {
  13664. evt.srcElement.setPointerCapture(evt.pointerId);
  13665. }
  13666. catch (e) {
  13667. }
  13668. // Manage panning with pan button click
  13669. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  13670. // manage pointers
  13671. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  13672. if (pointA === undefined) {
  13673. pointA = cacheSoloPointer;
  13674. }
  13675. else if (pointB === undefined) {
  13676. pointB = cacheSoloPointer;
  13677. }
  13678. if (!noPreventDefault) {
  13679. evt.preventDefault();
  13680. element.focus();
  13681. }
  13682. }
  13683. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13684. try {
  13685. evt.srcElement.releasePointerCapture(evt.pointerId);
  13686. }
  13687. catch (e) {
  13688. }
  13689. cacheSoloPointer = null;
  13690. previousPinchDistance = 0;
  13691. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  13692. //but emptying completly pointers collection is required to fix a bug on iPhone :
  13693. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  13694. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  13695. pointA = pointB = undefined;
  13696. if (!noPreventDefault) {
  13697. evt.preventDefault();
  13698. }
  13699. }
  13700. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13701. if (!noPreventDefault) {
  13702. evt.preventDefault();
  13703. }
  13704. // One button down
  13705. if (pointA && pointB === undefined) {
  13706. if (_this.panningSensibility !== 0 &&
  13707. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  13708. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  13709. _this.camera
  13710. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  13711. _this.camera
  13712. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  13713. }
  13714. else {
  13715. var offsetX = evt.clientX - cacheSoloPointer.x;
  13716. var offsetY = evt.clientY - cacheSoloPointer.y;
  13717. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13718. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13719. }
  13720. cacheSoloPointer.x = evt.clientX;
  13721. cacheSoloPointer.y = evt.clientY;
  13722. }
  13723. else if (pointA && pointB) {
  13724. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  13725. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  13726. ed.x = evt.clientX;
  13727. ed.y = evt.clientY;
  13728. var direction = _this.pinchInwards ? 1 : -1;
  13729. var distX = pointA.x - pointB.x;
  13730. var distY = pointA.y - pointB.y;
  13731. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  13732. if (previousPinchDistance === 0) {
  13733. previousPinchDistance = pinchSquaredDistance;
  13734. return;
  13735. }
  13736. if (pinchSquaredDistance !== previousPinchDistance) {
  13737. _this.camera
  13738. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  13739. (_this.pinchPrecision *
  13740. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  13741. direction);
  13742. previousPinchDistance = pinchSquaredDistance;
  13743. }
  13744. }
  13745. }
  13746. };
  13747. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13748. this._onContextMenu = function (evt) {
  13749. evt.preventDefault();
  13750. };
  13751. if (!this.camera._useCtrlForPanning) {
  13752. element.addEventListener("contextmenu", this._onContextMenu, false);
  13753. }
  13754. this._onLostFocus = function () {
  13755. //this._keys = [];
  13756. pointA = pointB = undefined;
  13757. previousPinchDistance = 0;
  13758. cacheSoloPointer = null;
  13759. };
  13760. this._onMouseMove = function (evt) {
  13761. if (!engine.isPointerLock) {
  13762. return;
  13763. }
  13764. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13765. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13766. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  13767. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  13768. if (!noPreventDefault) {
  13769. evt.preventDefault();
  13770. }
  13771. };
  13772. this._onGestureStart = function (e) {
  13773. if (window.MSGesture === undefined) {
  13774. return;
  13775. }
  13776. if (!_this._MSGestureHandler) {
  13777. _this._MSGestureHandler = new MSGesture();
  13778. _this._MSGestureHandler.target = element;
  13779. }
  13780. _this._MSGestureHandler.addPointer(e.pointerId);
  13781. };
  13782. this._onGesture = function (e) {
  13783. _this.camera.radius *= e.scale;
  13784. if (e.preventDefault) {
  13785. if (!noPreventDefault) {
  13786. e.stopPropagation();
  13787. e.preventDefault();
  13788. }
  13789. }
  13790. };
  13791. element.addEventListener("mousemove", this._onMouseMove, false);
  13792. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  13793. element.addEventListener("MSGestureChange", this._onGesture, false);
  13794. element.addEventListener("keydown", this._onKeyDown, false);
  13795. element.addEventListener("keyup", this._onKeyUp, false);
  13796. BABYLON.Tools.RegisterTopRootEvents([
  13797. { name: "blur", handler: this._onLostFocus }
  13798. ]);
  13799. };
  13800. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  13801. if (element && this._observer) {
  13802. this.camera.getScene().onPointerObservable.remove(this._observer);
  13803. this._observer = null;
  13804. element.removeEventListener("contextmenu", this._onContextMenu);
  13805. element.removeEventListener("mousemove", this._onMouseMove);
  13806. element.removeEventListener("MSPointerDown", this._onGestureStart);
  13807. element.removeEventListener("MSGestureChange", this._onGesture);
  13808. element.removeEventListener("keydown", this._onKeyDown);
  13809. element.removeEventListener("keyup", this._onKeyUp);
  13810. this._isPanClick = false;
  13811. this.pinchInwards = true;
  13812. this._onKeyDown = null;
  13813. this._onKeyUp = null;
  13814. this._onMouseMove = null;
  13815. this._onGestureStart = null;
  13816. this._onGesture = null;
  13817. this._MSGestureHandler = null;
  13818. this._onLostFocus = null;
  13819. this._onContextMenu = null;
  13820. }
  13821. BABYLON.Tools.UnregisterTopRootEvents([
  13822. { name: "blur", handler: this._onLostFocus }
  13823. ]);
  13824. };
  13825. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  13826. return "ArcRotateCameraPointersInput";
  13827. };
  13828. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  13829. return "pointers";
  13830. };
  13831. __decorate([
  13832. BABYLON.serialize()
  13833. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  13834. __decorate([
  13835. BABYLON.serialize()
  13836. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  13837. __decorate([
  13838. BABYLON.serialize()
  13839. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  13840. __decorate([
  13841. BABYLON.serialize()
  13842. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  13843. return ArcRotateCameraPointersInput;
  13844. }());
  13845. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  13846. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  13847. })(BABYLON || (BABYLON = {}));
  13848. var BABYLON;
  13849. (function (BABYLON) {
  13850. var ArcRotateCameraGamepadInput = (function () {
  13851. function ArcRotateCameraGamepadInput() {
  13852. this.gamepadRotationSensibility = 80;
  13853. this.gamepadMoveSensibility = 40;
  13854. }
  13855. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13856. var _this = this;
  13857. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13858. };
  13859. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  13860. if (this._gamepads) {
  13861. this._gamepads.dispose();
  13862. }
  13863. this.gamepad = null;
  13864. };
  13865. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  13866. if (this.gamepad) {
  13867. var camera = this.camera;
  13868. var RSValues = this.gamepad.rightStick;
  13869. if (RSValues.x != 0) {
  13870. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  13871. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  13872. camera.inertialAlphaOffset += normalizedRX;
  13873. }
  13874. }
  13875. if (RSValues.y != 0) {
  13876. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  13877. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  13878. camera.inertialBetaOffset += normalizedRY;
  13879. }
  13880. }
  13881. var LSValues = this.gamepad.leftStick;
  13882. if (LSValues.y != 0) {
  13883. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13884. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  13885. this.camera.inertialRadiusOffset -= normalizedLY;
  13886. }
  13887. }
  13888. }
  13889. };
  13890. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13891. // Only the first gamepad can control the camera
  13892. if (gamepad.index === 0) {
  13893. this.gamepad = gamepad;
  13894. }
  13895. };
  13896. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  13897. return "ArcRotateCameraGamepadInput";
  13898. };
  13899. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  13900. return "gamepad";
  13901. };
  13902. __decorate([
  13903. BABYLON.serialize()
  13904. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  13905. __decorate([
  13906. BABYLON.serialize()
  13907. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13908. return ArcRotateCameraGamepadInput;
  13909. }());
  13910. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  13911. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  13912. })(BABYLON || (BABYLON = {}));
  13913. var BABYLON;
  13914. (function (BABYLON) {
  13915. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  13916. function ArcRotateCameraVRDeviceOrientationInput() {
  13917. this.alphaCorrection = 1;
  13918. this.betaCorrection = 1;
  13919. this.gammaCorrection = 1;
  13920. this._alpha = 0;
  13921. this._beta = 0;
  13922. this._gamma = 0;
  13923. this._dirty = false;
  13924. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  13925. }
  13926. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13927. this.camera.attachControl(element, noPreventDefault);
  13928. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  13929. };
  13930. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  13931. var camera = this.camera;
  13932. this._alpha = +evt.alpha | 0;
  13933. this._beta = +evt.beta | 0;
  13934. this._gamma = +evt.gamma | 0;
  13935. this._dirty = true;
  13936. };
  13937. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  13938. if (this._dirty) {
  13939. this._dirty = false;
  13940. if (this._gamma < 0) {
  13941. this._gamma = 180 + this._gamma;
  13942. }
  13943. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  13944. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  13945. }
  13946. };
  13947. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  13948. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  13949. };
  13950. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  13951. return "ArcRotateCameraVRDeviceOrientationInput";
  13952. };
  13953. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  13954. return "VRDeviceOrientation";
  13955. };
  13956. return ArcRotateCameraVRDeviceOrientationInput;
  13957. }());
  13958. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  13959. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  13960. })(BABYLON || (BABYLON = {}));
  13961. var BABYLON;
  13962. (function (BABYLON) {
  13963. var TargetCamera = (function (_super) {
  13964. __extends(TargetCamera, _super);
  13965. function TargetCamera(name, position, scene) {
  13966. _super.call(this, name, position, scene);
  13967. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  13968. this.cameraRotation = new BABYLON.Vector2(0, 0);
  13969. this.rotation = new BABYLON.Vector3(0, 0, 0);
  13970. this.speed = 2.0;
  13971. this.noRotationConstraint = false;
  13972. this.lockedTarget = null;
  13973. this._currentTarget = BABYLON.Vector3.Zero();
  13974. this._viewMatrix = BABYLON.Matrix.Zero();
  13975. this._camMatrix = BABYLON.Matrix.Zero();
  13976. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  13977. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  13978. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  13979. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  13980. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  13981. this._lookAtTemp = BABYLON.Matrix.Zero();
  13982. this._tempMatrix = BABYLON.Matrix.Zero();
  13983. }
  13984. TargetCamera.prototype.getFrontPosition = function (distance) {
  13985. var direction = this.getTarget().subtract(this.position);
  13986. direction.normalize();
  13987. direction.scaleInPlace(distance);
  13988. return this.globalPosition.add(direction);
  13989. };
  13990. TargetCamera.prototype._getLockedTargetPosition = function () {
  13991. if (!this.lockedTarget) {
  13992. return null;
  13993. }
  13994. return this.lockedTarget.position || this.lockedTarget;
  13995. };
  13996. // Cache
  13997. TargetCamera.prototype._initCache = function () {
  13998. _super.prototype._initCache.call(this);
  13999. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14000. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14001. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14002. };
  14003. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14004. if (!ignoreParentClass) {
  14005. _super.prototype._updateCache.call(this);
  14006. }
  14007. var lockedTargetPosition = this._getLockedTargetPosition();
  14008. if (!lockedTargetPosition) {
  14009. this._cache.lockedTarget = null;
  14010. }
  14011. else {
  14012. if (!this._cache.lockedTarget) {
  14013. this._cache.lockedTarget = lockedTargetPosition.clone();
  14014. }
  14015. else {
  14016. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14017. }
  14018. }
  14019. this._cache.rotation.copyFrom(this.rotation);
  14020. if (this.rotationQuaternion)
  14021. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14022. };
  14023. // Synchronized
  14024. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14025. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14026. return false;
  14027. }
  14028. var lockedTargetPosition = this._getLockedTargetPosition();
  14029. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14030. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14031. };
  14032. // Methods
  14033. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14034. var engine = this.getEngine();
  14035. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14036. };
  14037. // Target
  14038. TargetCamera.prototype.setTarget = function (target) {
  14039. this.upVector.normalize();
  14040. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14041. this._camMatrix.invert();
  14042. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14043. var vDir = target.subtract(this.position);
  14044. if (vDir.x >= 0.0) {
  14045. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14046. }
  14047. else {
  14048. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14049. }
  14050. this.rotation.z = 0;
  14051. if (isNaN(this.rotation.x)) {
  14052. this.rotation.x = 0;
  14053. }
  14054. if (isNaN(this.rotation.y)) {
  14055. this.rotation.y = 0;
  14056. }
  14057. if (isNaN(this.rotation.z)) {
  14058. this.rotation.z = 0;
  14059. }
  14060. if (this.rotationQuaternion) {
  14061. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14062. }
  14063. };
  14064. TargetCamera.prototype.getTarget = function () {
  14065. return this._currentTarget;
  14066. };
  14067. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14068. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14069. };
  14070. TargetCamera.prototype._updatePosition = function () {
  14071. this.position.addInPlace(this.cameraDirection);
  14072. };
  14073. TargetCamera.prototype._checkInputs = function () {
  14074. var needToMove = this._decideIfNeedsToMove();
  14075. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14076. // Move
  14077. if (needToMove) {
  14078. this._updatePosition();
  14079. }
  14080. // Rotate
  14081. if (needToRotate) {
  14082. this.rotation.x += this.cameraRotation.x;
  14083. this.rotation.y += this.cameraRotation.y;
  14084. if (!this.noRotationConstraint) {
  14085. var limit = (Math.PI / 2) * 0.95;
  14086. if (this.rotation.x > limit)
  14087. this.rotation.x = limit;
  14088. if (this.rotation.x < -limit)
  14089. this.rotation.x = -limit;
  14090. }
  14091. }
  14092. // Inertia
  14093. if (needToMove) {
  14094. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14095. this.cameraDirection.x = 0;
  14096. }
  14097. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14098. this.cameraDirection.y = 0;
  14099. }
  14100. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14101. this.cameraDirection.z = 0;
  14102. }
  14103. this.cameraDirection.scaleInPlace(this.inertia);
  14104. }
  14105. if (needToRotate) {
  14106. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14107. this.cameraRotation.x = 0;
  14108. }
  14109. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14110. this.cameraRotation.y = 0;
  14111. }
  14112. this.cameraRotation.scaleInPlace(this.inertia);
  14113. }
  14114. _super.prototype._checkInputs.call(this);
  14115. };
  14116. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14117. if (this.rotationQuaternion) {
  14118. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14119. //update the up vector!
  14120. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14121. }
  14122. else {
  14123. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14124. }
  14125. };
  14126. TargetCamera.prototype._getViewMatrix = function () {
  14127. if (!this.lockedTarget) {
  14128. // Compute
  14129. this._updateCameraRotationMatrix();
  14130. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14131. // Computing target and final matrix
  14132. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14133. }
  14134. else {
  14135. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14136. }
  14137. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14138. return this._viewMatrix;
  14139. };
  14140. /**
  14141. * @override
  14142. * Override Camera.createRigCamera
  14143. */
  14144. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14145. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14146. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14147. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14148. if (!this.rotationQuaternion) {
  14149. this.rotationQuaternion = new BABYLON.Quaternion();
  14150. }
  14151. rigCamera._cameraRigParams = {};
  14152. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14153. }
  14154. return rigCamera;
  14155. }
  14156. return null;
  14157. };
  14158. /**
  14159. * @override
  14160. * Override Camera._updateRigCameras
  14161. */
  14162. TargetCamera.prototype._updateRigCameras = function () {
  14163. var camLeft = this._rigCameras[0];
  14164. var camRight = this._rigCameras[1];
  14165. switch (this.cameraRigMode) {
  14166. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14167. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14168. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14169. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14170. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14171. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14172. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14173. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14174. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14175. camLeft.setTarget(this.getTarget());
  14176. camRight.setTarget(this.getTarget());
  14177. break;
  14178. case BABYLON.Camera.RIG_MODE_VR:
  14179. case BABYLON.Camera.RIG_MODE_WEBVR:
  14180. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14181. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14182. camLeft.position.copyFrom(this.position);
  14183. camRight.position.copyFrom(this.position);
  14184. break;
  14185. }
  14186. _super.prototype._updateRigCameras.call(this);
  14187. };
  14188. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14189. if (!this._rigCamTransformMatrix) {
  14190. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14191. }
  14192. var target = this.getTarget();
  14193. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14194. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14195. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14196. };
  14197. TargetCamera.prototype.getTypeName = function () {
  14198. return "TargetCamera";
  14199. };
  14200. __decorate([
  14201. BABYLON.serializeAsVector3()
  14202. ], TargetCamera.prototype, "rotation", void 0);
  14203. __decorate([
  14204. BABYLON.serialize()
  14205. ], TargetCamera.prototype, "speed", void 0);
  14206. __decorate([
  14207. BABYLON.serializeAsMeshReference("lockedTargetId")
  14208. ], TargetCamera.prototype, "lockedTarget", void 0);
  14209. return TargetCamera;
  14210. }(BABYLON.Camera));
  14211. BABYLON.TargetCamera = TargetCamera;
  14212. })(BABYLON || (BABYLON = {}));
  14213. var BABYLON;
  14214. (function (BABYLON) {
  14215. var FreeCamera = (function (_super) {
  14216. __extends(FreeCamera, _super);
  14217. function FreeCamera(name, position, scene) {
  14218. var _this = this;
  14219. _super.call(this, name, position, scene);
  14220. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14221. this.checkCollisions = false;
  14222. this.applyGravity = false;
  14223. this._collider = new BABYLON.Collider();
  14224. this._needMoveForGravity = false;
  14225. this._oldPosition = BABYLON.Vector3.Zero();
  14226. this._diffPosition = BABYLON.Vector3.Zero();
  14227. this._newPosition = BABYLON.Vector3.Zero();
  14228. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14229. if (collidedMesh === void 0) { collidedMesh = null; }
  14230. //TODO move this to the collision coordinator!
  14231. if (_this.getScene().workerCollisions)
  14232. newPosition.multiplyInPlace(_this._collider.radius);
  14233. var updatePosition = function (newPos) {
  14234. _this._newPosition.copyFrom(newPos);
  14235. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14236. var oldPosition = _this.position.clone();
  14237. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14238. _this.position.addInPlace(_this._diffPosition);
  14239. if (_this.onCollide && collidedMesh) {
  14240. _this.onCollide(collidedMesh);
  14241. }
  14242. }
  14243. };
  14244. updatePosition(newPosition);
  14245. };
  14246. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14247. this.inputs.addKeyboard().addMouse();
  14248. }
  14249. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14250. //-- begin properties for backward compatibility for inputs
  14251. get: function () {
  14252. var mouse = this.inputs.attached["mouse"];
  14253. if (mouse)
  14254. return mouse.angularSensibility;
  14255. },
  14256. set: function (value) {
  14257. var mouse = this.inputs.attached["mouse"];
  14258. if (mouse)
  14259. mouse.angularSensibility = value;
  14260. },
  14261. enumerable: true,
  14262. configurable: true
  14263. });
  14264. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14265. get: function () {
  14266. var keyboard = this.inputs.attached["keyboard"];
  14267. if (keyboard)
  14268. return keyboard.keysUp;
  14269. },
  14270. set: function (value) {
  14271. var keyboard = this.inputs.attached["keyboard"];
  14272. if (keyboard)
  14273. keyboard.keysUp = value;
  14274. },
  14275. enumerable: true,
  14276. configurable: true
  14277. });
  14278. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14279. get: function () {
  14280. var keyboard = this.inputs.attached["keyboard"];
  14281. if (keyboard)
  14282. return keyboard.keysDown;
  14283. },
  14284. set: function (value) {
  14285. var keyboard = this.inputs.attached["keyboard"];
  14286. if (keyboard)
  14287. keyboard.keysDown = value;
  14288. },
  14289. enumerable: true,
  14290. configurable: true
  14291. });
  14292. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14293. get: function () {
  14294. var keyboard = this.inputs.attached["keyboard"];
  14295. if (keyboard)
  14296. return keyboard.keysLeft;
  14297. },
  14298. set: function (value) {
  14299. var keyboard = this.inputs.attached["keyboard"];
  14300. if (keyboard)
  14301. keyboard.keysLeft = value;
  14302. },
  14303. enumerable: true,
  14304. configurable: true
  14305. });
  14306. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14307. get: function () {
  14308. var keyboard = this.inputs.attached["keyboard"];
  14309. if (keyboard)
  14310. return keyboard.keysRight;
  14311. },
  14312. set: function (value) {
  14313. var keyboard = this.inputs.attached["keyboard"];
  14314. if (keyboard)
  14315. keyboard.keysRight = value;
  14316. },
  14317. enumerable: true,
  14318. configurable: true
  14319. });
  14320. // Controls
  14321. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14322. this.inputs.attachElement(element, noPreventDefault);
  14323. };
  14324. FreeCamera.prototype.detachControl = function (element) {
  14325. this.inputs.detachElement(element);
  14326. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14327. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14328. };
  14329. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14330. var globalPosition;
  14331. if (this.parent) {
  14332. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14333. }
  14334. else {
  14335. globalPosition = this.position;
  14336. }
  14337. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14338. this._collider.radius = this.ellipsoid;
  14339. //no need for clone, as long as gravity is not on.
  14340. var actualVelocity = velocity;
  14341. //add gravity to the velocity to prevent the dual-collision checking
  14342. if (this.applyGravity) {
  14343. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14344. actualVelocity = velocity.add(this.getScene().gravity);
  14345. }
  14346. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14347. };
  14348. FreeCamera.prototype._checkInputs = function () {
  14349. if (!this._localDirection) {
  14350. this._localDirection = BABYLON.Vector3.Zero();
  14351. this._transformedDirection = BABYLON.Vector3.Zero();
  14352. }
  14353. this.inputs.checkInputs();
  14354. _super.prototype._checkInputs.call(this);
  14355. };
  14356. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14357. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14358. };
  14359. FreeCamera.prototype._updatePosition = function () {
  14360. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14361. this._collideWithWorld(this.cameraDirection);
  14362. }
  14363. else {
  14364. this.position.addInPlace(this.cameraDirection);
  14365. }
  14366. };
  14367. FreeCamera.prototype.dispose = function () {
  14368. this.inputs.clear();
  14369. _super.prototype.dispose.call(this);
  14370. };
  14371. FreeCamera.prototype.getTypeName = function () {
  14372. return "FreeCamera";
  14373. };
  14374. __decorate([
  14375. BABYLON.serializeAsVector3()
  14376. ], FreeCamera.prototype, "ellipsoid", void 0);
  14377. __decorate([
  14378. BABYLON.serialize()
  14379. ], FreeCamera.prototype, "checkCollisions", void 0);
  14380. __decorate([
  14381. BABYLON.serialize()
  14382. ], FreeCamera.prototype, "applyGravity", void 0);
  14383. return FreeCamera;
  14384. }(BABYLON.TargetCamera));
  14385. BABYLON.FreeCamera = FreeCamera;
  14386. })(BABYLON || (BABYLON = {}));
  14387. var BABYLON;
  14388. (function (BABYLON) {
  14389. var FreeCameraInputsManager = (function (_super) {
  14390. __extends(FreeCameraInputsManager, _super);
  14391. function FreeCameraInputsManager(camera) {
  14392. _super.call(this, camera);
  14393. }
  14394. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14395. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14396. return this;
  14397. };
  14398. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14399. if (touchEnabled === void 0) { touchEnabled = true; }
  14400. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14401. return this;
  14402. };
  14403. FreeCameraInputsManager.prototype.addGamepad = function () {
  14404. this.add(new BABYLON.FreeCameraGamepadInput());
  14405. return this;
  14406. };
  14407. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14408. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14409. return this;
  14410. };
  14411. FreeCameraInputsManager.prototype.addTouch = function () {
  14412. this.add(new BABYLON.FreeCameraTouchInput());
  14413. return this;
  14414. };
  14415. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14416. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14417. return this;
  14418. };
  14419. return FreeCameraInputsManager;
  14420. }(BABYLON.CameraInputsManager));
  14421. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14422. })(BABYLON || (BABYLON = {}));
  14423. var BABYLON;
  14424. (function (BABYLON) {
  14425. var FollowCamera = (function (_super) {
  14426. __extends(FollowCamera, _super);
  14427. function FollowCamera(name, position, scene, target) {
  14428. _super.call(this, name, position, scene);
  14429. this.radius = 12;
  14430. this.rotationOffset = 0;
  14431. this.heightOffset = 4;
  14432. this.cameraAcceleration = 0.05;
  14433. this.maxCameraSpeed = 20;
  14434. this.target = target;
  14435. }
  14436. FollowCamera.prototype.getRadians = function (degrees) {
  14437. return degrees * Math.PI / 180;
  14438. };
  14439. FollowCamera.prototype.follow = function (cameraTarget) {
  14440. if (!cameraTarget)
  14441. return;
  14442. var yRotation;
  14443. if (cameraTarget.rotationQuaternion) {
  14444. var rotMatrix = new BABYLON.Matrix();
  14445. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14446. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14447. }
  14448. else {
  14449. yRotation = cameraTarget.rotation.y;
  14450. }
  14451. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14452. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14453. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14454. var dx = targetX - this.position.x;
  14455. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14456. var dz = (targetZ) - this.position.z;
  14457. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14458. var vy = dy * this.cameraAcceleration;
  14459. var vz = dz * this.cameraAcceleration * 2;
  14460. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14461. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14462. }
  14463. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14464. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14465. }
  14466. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14467. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14468. }
  14469. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14470. this.setTarget(cameraTarget.position);
  14471. };
  14472. FollowCamera.prototype._checkInputs = function () {
  14473. _super.prototype._checkInputs.call(this);
  14474. this.follow(this.target);
  14475. };
  14476. FollowCamera.prototype.getTypeName = function () {
  14477. return "FollowCamera";
  14478. };
  14479. __decorate([
  14480. BABYLON.serialize()
  14481. ], FollowCamera.prototype, "radius", void 0);
  14482. __decorate([
  14483. BABYLON.serialize()
  14484. ], FollowCamera.prototype, "rotationOffset", void 0);
  14485. __decorate([
  14486. BABYLON.serialize()
  14487. ], FollowCamera.prototype, "heightOffset", void 0);
  14488. __decorate([
  14489. BABYLON.serialize()
  14490. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14491. __decorate([
  14492. BABYLON.serialize()
  14493. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14494. __decorate([
  14495. BABYLON.serializeAsMeshReference("lockedTargetId")
  14496. ], FollowCamera.prototype, "target", void 0);
  14497. return FollowCamera;
  14498. }(BABYLON.TargetCamera));
  14499. BABYLON.FollowCamera = FollowCamera;
  14500. var ArcFollowCamera = (function (_super) {
  14501. __extends(ArcFollowCamera, _super);
  14502. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14503. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14504. this.alpha = alpha;
  14505. this.beta = beta;
  14506. this.radius = radius;
  14507. this.target = target;
  14508. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14509. this.follow();
  14510. }
  14511. ArcFollowCamera.prototype.follow = function () {
  14512. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14513. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14514. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14515. this.position = this.target.position.add(this._cartesianCoordinates);
  14516. this.setTarget(this.target.position);
  14517. };
  14518. ArcFollowCamera.prototype._checkInputs = function () {
  14519. _super.prototype._checkInputs.call(this);
  14520. this.follow();
  14521. };
  14522. ArcFollowCamera.prototype.getTypeName = function () {
  14523. return "ArcFollowCamera";
  14524. };
  14525. return ArcFollowCamera;
  14526. }(BABYLON.TargetCamera));
  14527. BABYLON.ArcFollowCamera = ArcFollowCamera;
  14528. })(BABYLON || (BABYLON = {}));
  14529. var BABYLON;
  14530. (function (BABYLON) {
  14531. // We're mainly based on the logic defined into the FreeCamera code
  14532. var TouchCamera = (function (_super) {
  14533. __extends(TouchCamera, _super);
  14534. //-- end properties for backward compatibility for inputs
  14535. function TouchCamera(name, position, scene) {
  14536. _super.call(this, name, position, scene);
  14537. this.inputs.addTouch();
  14538. this._setupInputs();
  14539. }
  14540. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  14541. //-- Begin properties for backward compatibility for inputs
  14542. get: function () {
  14543. var touch = this.inputs.attached["touch"];
  14544. if (touch)
  14545. return touch.touchAngularSensibility;
  14546. },
  14547. set: function (value) {
  14548. var touch = this.inputs.attached["touch"];
  14549. if (touch)
  14550. touch.touchAngularSensibility = value;
  14551. },
  14552. enumerable: true,
  14553. configurable: true
  14554. });
  14555. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  14556. get: function () {
  14557. var touch = this.inputs.attached["touch"];
  14558. if (touch)
  14559. return touch.touchMoveSensibility;
  14560. },
  14561. set: function (value) {
  14562. var touch = this.inputs.attached["touch"];
  14563. if (touch)
  14564. touch.touchMoveSensibility = value;
  14565. },
  14566. enumerable: true,
  14567. configurable: true
  14568. });
  14569. TouchCamera.prototype.getTypeName = function () {
  14570. return "TouchCamera";
  14571. };
  14572. TouchCamera.prototype._setupInputs = function () {
  14573. var mouse = this.inputs.attached["mouse"];
  14574. if (mouse) {
  14575. mouse.touchEnabled = false;
  14576. }
  14577. };
  14578. return TouchCamera;
  14579. }(BABYLON.FreeCamera));
  14580. BABYLON.TouchCamera = TouchCamera;
  14581. })(BABYLON || (BABYLON = {}));
  14582. var BABYLON;
  14583. (function (BABYLON) {
  14584. var ArcRotateCamera = (function (_super) {
  14585. __extends(ArcRotateCamera, _super);
  14586. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  14587. var _this = this;
  14588. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14589. this.inertialAlphaOffset = 0;
  14590. this.inertialBetaOffset = 0;
  14591. this.inertialRadiusOffset = 0;
  14592. this.lowerAlphaLimit = null;
  14593. this.upperAlphaLimit = null;
  14594. this.lowerBetaLimit = 0.01;
  14595. this.upperBetaLimit = Math.PI;
  14596. this.lowerRadiusLimit = null;
  14597. this.upperRadiusLimit = null;
  14598. this.inertialPanningX = 0;
  14599. this.inertialPanningY = 0;
  14600. //-- end properties for backward compatibility for inputs
  14601. this.zoomOnFactor = 1;
  14602. this.targetScreenOffset = BABYLON.Vector2.Zero();
  14603. this.allowUpsideDown = true;
  14604. this._viewMatrix = new BABYLON.Matrix();
  14605. // Panning
  14606. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  14607. this.checkCollisions = false;
  14608. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14609. this._collider = new BABYLON.Collider();
  14610. this._previousPosition = BABYLON.Vector3.Zero();
  14611. this._collisionVelocity = BABYLON.Vector3.Zero();
  14612. this._newPosition = BABYLON.Vector3.Zero();
  14613. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14614. if (collidedMesh === void 0) { collidedMesh = null; }
  14615. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  14616. newPosition.multiplyInPlace(_this._collider.radius);
  14617. }
  14618. if (!collidedMesh) {
  14619. _this._previousPosition.copyFrom(_this.position);
  14620. }
  14621. else {
  14622. _this.setPosition(newPosition);
  14623. if (_this.onCollide) {
  14624. _this.onCollide(collidedMesh);
  14625. }
  14626. }
  14627. // Recompute because of constraints
  14628. var cosa = Math.cos(_this.alpha);
  14629. var sina = Math.sin(_this.alpha);
  14630. var cosb = Math.cos(_this.beta);
  14631. var sinb = Math.sin(_this.beta);
  14632. if (sinb === 0) {
  14633. sinb = 0.0001;
  14634. }
  14635. var target = _this._getTargetPosition();
  14636. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  14637. _this.position.copyFrom(_this._newPosition);
  14638. var up = _this.upVector;
  14639. if (_this.allowUpsideDown && _this.beta < 0) {
  14640. up = up.clone();
  14641. up = up.negate();
  14642. }
  14643. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  14644. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  14645. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  14646. _this._collisionTriggered = false;
  14647. };
  14648. if (!target) {
  14649. this.target = BABYLON.Vector3.Zero();
  14650. }
  14651. else {
  14652. this.target = target;
  14653. }
  14654. this.alpha = alpha;
  14655. this.beta = beta;
  14656. this.radius = radius;
  14657. this.getViewMatrix();
  14658. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  14659. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  14660. }
  14661. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  14662. //-- begin properties for backward compatibility for inputs
  14663. get: function () {
  14664. var pointers = this.inputs.attached["pointers"];
  14665. if (pointers)
  14666. return pointers.angularSensibilityX;
  14667. },
  14668. set: function (value) {
  14669. var pointers = this.inputs.attached["pointers"];
  14670. if (pointers) {
  14671. pointers.angularSensibilityX = value;
  14672. }
  14673. },
  14674. enumerable: true,
  14675. configurable: true
  14676. });
  14677. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  14678. get: function () {
  14679. var pointers = this.inputs.attached["pointers"];
  14680. if (pointers)
  14681. return pointers.angularSensibilityY;
  14682. },
  14683. set: function (value) {
  14684. var pointers = this.inputs.attached["pointers"];
  14685. if (pointers) {
  14686. pointers.angularSensibilityY = value;
  14687. }
  14688. },
  14689. enumerable: true,
  14690. configurable: true
  14691. });
  14692. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  14693. get: function () {
  14694. var pointers = this.inputs.attached["pointers"];
  14695. if (pointers)
  14696. return pointers.pinchPrecision;
  14697. },
  14698. set: function (value) {
  14699. var pointers = this.inputs.attached["pointers"];
  14700. if (pointers) {
  14701. pointers.pinchPrecision = value;
  14702. }
  14703. },
  14704. enumerable: true,
  14705. configurable: true
  14706. });
  14707. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  14708. get: function () {
  14709. var pointers = this.inputs.attached["pointers"];
  14710. if (pointers)
  14711. return pointers.panningSensibility;
  14712. },
  14713. set: function (value) {
  14714. var pointers = this.inputs.attached["pointers"];
  14715. if (pointers) {
  14716. pointers.panningSensibility = value;
  14717. }
  14718. },
  14719. enumerable: true,
  14720. configurable: true
  14721. });
  14722. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  14723. get: function () {
  14724. var keyboard = this.inputs.attached["keyboard"];
  14725. if (keyboard)
  14726. return keyboard.keysUp;
  14727. },
  14728. set: function (value) {
  14729. var keyboard = this.inputs.attached["keyboard"];
  14730. if (keyboard)
  14731. keyboard.keysUp = value;
  14732. },
  14733. enumerable: true,
  14734. configurable: true
  14735. });
  14736. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  14737. get: function () {
  14738. var keyboard = this.inputs.attached["keyboard"];
  14739. if (keyboard)
  14740. return keyboard.keysDown;
  14741. },
  14742. set: function (value) {
  14743. var keyboard = this.inputs.attached["keyboard"];
  14744. if (keyboard)
  14745. keyboard.keysDown = value;
  14746. },
  14747. enumerable: true,
  14748. configurable: true
  14749. });
  14750. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  14751. get: function () {
  14752. var keyboard = this.inputs.attached["keyboard"];
  14753. if (keyboard)
  14754. return keyboard.keysLeft;
  14755. },
  14756. set: function (value) {
  14757. var keyboard = this.inputs.attached["keyboard"];
  14758. if (keyboard)
  14759. keyboard.keysLeft = value;
  14760. },
  14761. enumerable: true,
  14762. configurable: true
  14763. });
  14764. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  14765. get: function () {
  14766. var keyboard = this.inputs.attached["keyboard"];
  14767. if (keyboard)
  14768. return keyboard.keysRight;
  14769. },
  14770. set: function (value) {
  14771. var keyboard = this.inputs.attached["keyboard"];
  14772. if (keyboard)
  14773. keyboard.keysRight = value;
  14774. },
  14775. enumerable: true,
  14776. configurable: true
  14777. });
  14778. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  14779. get: function () {
  14780. var mousewheel = this.inputs.attached["mousewheel"];
  14781. if (mousewheel)
  14782. return mousewheel.wheelPrecision;
  14783. },
  14784. set: function (value) {
  14785. var mousewheel = this.inputs.attached["mousewheel"];
  14786. if (mousewheel)
  14787. mousewheel.wheelPrecision = value;
  14788. },
  14789. enumerable: true,
  14790. configurable: true
  14791. });
  14792. // Cache
  14793. ArcRotateCamera.prototype._initCache = function () {
  14794. _super.prototype._initCache.call(this);
  14795. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14796. this._cache.alpha = undefined;
  14797. this._cache.beta = undefined;
  14798. this._cache.radius = undefined;
  14799. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  14800. };
  14801. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  14802. if (!ignoreParentClass) {
  14803. _super.prototype._updateCache.call(this);
  14804. }
  14805. this._cache.target.copyFrom(this._getTargetPosition());
  14806. this._cache.alpha = this.alpha;
  14807. this._cache.beta = this.beta;
  14808. this._cache.radius = this.radius;
  14809. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  14810. };
  14811. ArcRotateCamera.prototype._getTargetPosition = function () {
  14812. if (this.target.getAbsolutePosition) {
  14813. return this.target.getAbsolutePosition();
  14814. }
  14815. return this.target;
  14816. };
  14817. // Synchronized
  14818. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  14819. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  14820. return false;
  14821. return this._cache.target.equals(this.target)
  14822. && this._cache.alpha === this.alpha
  14823. && this._cache.beta === this.beta
  14824. && this._cache.radius === this.radius
  14825. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  14826. };
  14827. // Methods
  14828. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  14829. var _this = this;
  14830. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  14831. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  14832. this._useCtrlForPanning = useCtrlForPanning;
  14833. this._panningMouseButton = panningMouseButton;
  14834. this.inputs.attachElement(element, noPreventDefault);
  14835. this._reset = function () {
  14836. _this.inertialAlphaOffset = 0;
  14837. _this.inertialBetaOffset = 0;
  14838. _this.inertialRadiusOffset = 0;
  14839. };
  14840. };
  14841. ArcRotateCamera.prototype.detachControl = function (element) {
  14842. this.inputs.detachElement(element);
  14843. if (this._reset) {
  14844. this._reset();
  14845. }
  14846. };
  14847. ArcRotateCamera.prototype._checkInputs = function () {
  14848. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  14849. if (this._collisionTriggered) {
  14850. return;
  14851. }
  14852. this.inputs.checkInputs();
  14853. // Inertia
  14854. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  14855. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  14856. this.beta += this.inertialBetaOffset;
  14857. this.radius -= this.inertialRadiusOffset;
  14858. this.inertialAlphaOffset *= this.inertia;
  14859. this.inertialBetaOffset *= this.inertia;
  14860. this.inertialRadiusOffset *= this.inertia;
  14861. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  14862. this.inertialAlphaOffset = 0;
  14863. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  14864. this.inertialBetaOffset = 0;
  14865. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  14866. this.inertialRadiusOffset = 0;
  14867. }
  14868. // Panning inertia
  14869. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  14870. if (!this._localDirection) {
  14871. this._localDirection = BABYLON.Vector3.Zero();
  14872. this._transformedDirection = BABYLON.Vector3.Zero();
  14873. }
  14874. this.inertialPanningX *= this.inertia;
  14875. this.inertialPanningY *= this.inertia;
  14876. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  14877. this.inertialPanningX = 0;
  14878. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  14879. this.inertialPanningY = 0;
  14880. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  14881. this._localDirection.multiplyInPlace(this.panningAxis);
  14882. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  14883. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  14884. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  14885. if (!this.panningAxis.y) {
  14886. this._transformedDirection.y = 0;
  14887. }
  14888. if (!this.target.getAbsolutePosition) {
  14889. this.target.addInPlace(this._transformedDirection);
  14890. }
  14891. }
  14892. // Limits
  14893. this._checkLimits();
  14894. _super.prototype._checkInputs.call(this);
  14895. };
  14896. ArcRotateCamera.prototype._checkLimits = function () {
  14897. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  14898. if (this.allowUpsideDown && this.beta > Math.PI) {
  14899. this.beta = this.beta - (2 * Math.PI);
  14900. }
  14901. }
  14902. else {
  14903. if (this.beta < this.lowerBetaLimit) {
  14904. this.beta = this.lowerBetaLimit;
  14905. }
  14906. }
  14907. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  14908. if (this.allowUpsideDown && this.beta < -Math.PI) {
  14909. this.beta = this.beta + (2 * Math.PI);
  14910. }
  14911. }
  14912. else {
  14913. if (this.beta > this.upperBetaLimit) {
  14914. this.beta = this.upperBetaLimit;
  14915. }
  14916. }
  14917. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  14918. this.alpha = this.lowerAlphaLimit;
  14919. }
  14920. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  14921. this.alpha = this.upperAlphaLimit;
  14922. }
  14923. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  14924. this.radius = this.lowerRadiusLimit;
  14925. }
  14926. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  14927. this.radius = this.upperRadiusLimit;
  14928. }
  14929. };
  14930. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  14931. var radiusv3 = this.position.subtract(this._getTargetPosition());
  14932. this.radius = radiusv3.length();
  14933. // Alpha
  14934. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  14935. if (radiusv3.z < 0) {
  14936. this.alpha = 2 * Math.PI - this.alpha;
  14937. }
  14938. // Beta
  14939. this.beta = Math.acos(radiusv3.y / this.radius);
  14940. this._checkLimits();
  14941. };
  14942. ArcRotateCamera.prototype.setPosition = function (position) {
  14943. if (this.position.equals(position)) {
  14944. return;
  14945. }
  14946. this.position.copyFrom(position);
  14947. this.rebuildAnglesAndRadius();
  14948. };
  14949. ArcRotateCamera.prototype.setTarget = function (target) {
  14950. if (this._getTargetPosition().equals(target)) {
  14951. return;
  14952. }
  14953. this.target = target;
  14954. this.rebuildAnglesAndRadius();
  14955. };
  14956. ArcRotateCamera.prototype._getViewMatrix = function () {
  14957. // Compute
  14958. var cosa = Math.cos(this.alpha);
  14959. var sina = Math.sin(this.alpha);
  14960. var cosb = Math.cos(this.beta);
  14961. var sinb = Math.sin(this.beta);
  14962. if (sinb === 0) {
  14963. sinb = 0.0001;
  14964. }
  14965. var target = this._getTargetPosition();
  14966. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  14967. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  14968. this._collider.radius = this.collisionRadius;
  14969. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  14970. this._collisionTriggered = true;
  14971. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14972. }
  14973. else {
  14974. this.position.copyFrom(this._newPosition);
  14975. var up = this.upVector;
  14976. if (this.allowUpsideDown && this.beta < 0) {
  14977. up = up.clone();
  14978. up = up.negate();
  14979. }
  14980. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  14981. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  14982. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  14983. }
  14984. return this._viewMatrix;
  14985. };
  14986. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  14987. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14988. meshes = meshes || this.getScene().meshes;
  14989. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  14990. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  14991. this.radius = distance * this.zoomOnFactor;
  14992. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  14993. };
  14994. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  14995. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  14996. var meshesOrMinMaxVector;
  14997. var distance;
  14998. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  14999. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15000. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15001. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15002. }
  15003. else {
  15004. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15005. distance = meshesOrMinMaxVectorAndDistance.distance;
  15006. }
  15007. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15008. if (!doNotUpdateMaxZ) {
  15009. this.maxZ = distance * 2;
  15010. }
  15011. };
  15012. /**
  15013. * @override
  15014. * Override Camera.createRigCamera
  15015. */
  15016. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15017. var alphaShift;
  15018. switch (this.cameraRigMode) {
  15019. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15020. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15021. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15022. case BABYLON.Camera.RIG_MODE_VR:
  15023. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15024. break;
  15025. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15026. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15027. break;
  15028. }
  15029. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15030. rigCam._cameraRigParams = {};
  15031. return rigCam;
  15032. };
  15033. /**
  15034. * @override
  15035. * Override Camera._updateRigCameras
  15036. */
  15037. ArcRotateCamera.prototype._updateRigCameras = function () {
  15038. var camLeft = this._rigCameras[0];
  15039. var camRight = this._rigCameras[1];
  15040. camLeft.beta = camRight.beta = this.beta;
  15041. camLeft.radius = camRight.radius = this.radius;
  15042. switch (this.cameraRigMode) {
  15043. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15044. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15045. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15046. case BABYLON.Camera.RIG_MODE_VR:
  15047. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15048. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15049. break;
  15050. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15051. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15052. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15053. break;
  15054. }
  15055. _super.prototype._updateRigCameras.call(this);
  15056. };
  15057. ArcRotateCamera.prototype.dispose = function () {
  15058. this.inputs.clear();
  15059. _super.prototype.dispose.call(this);
  15060. };
  15061. ArcRotateCamera.prototype.getTypeName = function () {
  15062. return "ArcRotateCamera";
  15063. };
  15064. __decorate([
  15065. BABYLON.serialize()
  15066. ], ArcRotateCamera.prototype, "alpha", void 0);
  15067. __decorate([
  15068. BABYLON.serialize()
  15069. ], ArcRotateCamera.prototype, "beta", void 0);
  15070. __decorate([
  15071. BABYLON.serialize()
  15072. ], ArcRotateCamera.prototype, "radius", void 0);
  15073. __decorate([
  15074. BABYLON.serializeAsVector3()
  15075. ], ArcRotateCamera.prototype, "target", void 0);
  15076. __decorate([
  15077. BABYLON.serialize()
  15078. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15079. __decorate([
  15080. BABYLON.serialize()
  15081. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15082. __decorate([
  15083. BABYLON.serialize()
  15084. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15085. __decorate([
  15086. BABYLON.serialize()
  15087. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15088. __decorate([
  15089. BABYLON.serialize()
  15090. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15091. __decorate([
  15092. BABYLON.serialize()
  15093. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15094. __decorate([
  15095. BABYLON.serialize()
  15096. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15097. __decorate([
  15098. BABYLON.serialize()
  15099. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15100. __decorate([
  15101. BABYLON.serialize()
  15102. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15103. __decorate([
  15104. BABYLON.serialize()
  15105. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15106. __decorate([
  15107. BABYLON.serialize()
  15108. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15109. __decorate([
  15110. BABYLON.serialize()
  15111. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15112. __decorate([
  15113. BABYLON.serialize()
  15114. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15115. return ArcRotateCamera;
  15116. }(BABYLON.TargetCamera));
  15117. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15118. })(BABYLON || (BABYLON = {}));
  15119. var BABYLON;
  15120. (function (BABYLON) {
  15121. var ArcRotateCameraInputsManager = (function (_super) {
  15122. __extends(ArcRotateCameraInputsManager, _super);
  15123. function ArcRotateCameraInputsManager(camera) {
  15124. _super.call(this, camera);
  15125. }
  15126. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15127. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15128. return this;
  15129. };
  15130. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15131. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15132. return this;
  15133. };
  15134. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15135. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15136. return this;
  15137. };
  15138. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15139. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15140. return this;
  15141. };
  15142. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15143. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15144. return this;
  15145. };
  15146. return ArcRotateCameraInputsManager;
  15147. }(BABYLON.CameraInputsManager));
  15148. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15149. })(BABYLON || (BABYLON = {}));
  15150. var BABYLON;
  15151. (function (BABYLON) {
  15152. var RenderingManager = (function () {
  15153. function RenderingManager(scene) {
  15154. this._renderingGroups = new Array();
  15155. this._autoClearDepthStencil = {};
  15156. this._customOpaqueSortCompareFn = {};
  15157. this._customAlphaTestSortCompareFn = {};
  15158. this._customTransparentSortCompareFn = {};
  15159. this._scene = scene;
  15160. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15161. this._autoClearDepthStencil[i] = true;
  15162. }
  15163. }
  15164. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15165. if (this._scene._activeParticleSystems.length === 0) {
  15166. return;
  15167. }
  15168. // Particles
  15169. var activeCamera = this._scene.activeCamera;
  15170. this._scene._particlesDuration.beginMonitoring();
  15171. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15172. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15173. if (particleSystem.renderingGroupId !== index) {
  15174. continue;
  15175. }
  15176. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15177. continue;
  15178. }
  15179. this._clearDepthStencilBuffer();
  15180. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15181. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15182. }
  15183. }
  15184. this._scene._particlesDuration.endMonitoring(false);
  15185. };
  15186. RenderingManager.prototype._renderSprites = function (index) {
  15187. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15188. return;
  15189. }
  15190. // Sprites
  15191. var activeCamera = this._scene.activeCamera;
  15192. this._scene._spritesDuration.beginMonitoring();
  15193. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15194. var spriteManager = this._scene.spriteManagers[id];
  15195. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15196. this._clearDepthStencilBuffer();
  15197. spriteManager.render();
  15198. }
  15199. }
  15200. this._scene._spritesDuration.endMonitoring(false);
  15201. };
  15202. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15203. if (this._depthStencilBufferAlreadyCleaned) {
  15204. return;
  15205. }
  15206. this._scene.getEngine().clear(0, false, true, true);
  15207. this._depthStencilBufferAlreadyCleaned = true;
  15208. };
  15209. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15210. if (this._currentRenderSprites) {
  15211. this._renderSprites(this._currentIndex);
  15212. }
  15213. if (this._currentRenderParticles) {
  15214. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15215. }
  15216. };
  15217. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15218. this._currentActiveMeshes = activeMeshes;
  15219. this._currentRenderParticles = renderParticles;
  15220. this._currentRenderSprites = renderSprites;
  15221. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15222. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15223. var renderingGroup = this._renderingGroups[index];
  15224. var needToStepBack = false;
  15225. this._currentIndex = index;
  15226. if (renderingGroup) {
  15227. if (this._autoClearDepthStencil[index]) {
  15228. this._clearDepthStencilBuffer();
  15229. }
  15230. if (!renderingGroup.onBeforeTransparentRendering) {
  15231. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15232. }
  15233. if (!renderingGroup.render(customRenderFunction)) {
  15234. this._renderingGroups.splice(index, 1);
  15235. needToStepBack = true;
  15236. this._renderSpritesAndParticles();
  15237. }
  15238. }
  15239. else {
  15240. this._renderSpritesAndParticles();
  15241. }
  15242. if (needToStepBack) {
  15243. index--;
  15244. }
  15245. }
  15246. };
  15247. RenderingManager.prototype.reset = function () {
  15248. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15249. var renderingGroup = this._renderingGroups[index];
  15250. if (renderingGroup) {
  15251. renderingGroup.prepare();
  15252. }
  15253. }
  15254. };
  15255. RenderingManager.prototype.dispatch = function (subMesh) {
  15256. var mesh = subMesh.getMesh();
  15257. var renderingGroupId = mesh.renderingGroupId || 0;
  15258. if (!this._renderingGroups[renderingGroupId]) {
  15259. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15260. }
  15261. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15262. };
  15263. /**
  15264. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15265. * This allowed control for front to back rendering or reversly depending of the special needs.
  15266. *
  15267. * @param renderingGroupId The rendering group id corresponding to its index
  15268. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15269. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15270. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15271. */
  15272. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15273. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15274. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15275. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15276. if (this._renderingGroups[renderingGroupId]) {
  15277. var group = this._renderingGroups[renderingGroupId];
  15278. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15279. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15280. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15281. }
  15282. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15283. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15284. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15285. };
  15286. /**
  15287. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15288. *
  15289. * @param renderingGroupId The rendering group id corresponding to its index
  15290. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15291. */
  15292. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15293. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15294. };
  15295. /**
  15296. * The max id used for rendering groups (not included)
  15297. */
  15298. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15299. /**
  15300. * The min id used for rendering groups (included)
  15301. */
  15302. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15303. return RenderingManager;
  15304. }());
  15305. BABYLON.RenderingManager = RenderingManager;
  15306. })(BABYLON || (BABYLON = {}));
  15307. var BABYLON;
  15308. (function (BABYLON) {
  15309. var RenderingGroup = (function () {
  15310. /**
  15311. * Creates a new rendering group.
  15312. * @param index The rendering group index
  15313. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15314. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15315. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15316. */
  15317. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15318. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15319. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15320. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15321. this.index = index;
  15322. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15323. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15324. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15325. this._scene = scene;
  15326. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15327. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15328. this.transparentSortCompareFn = transparentSortCompareFn;
  15329. }
  15330. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15331. /**
  15332. * Set the opaque sort comparison function.
  15333. * If null the sub meshes will be render in the order they were created
  15334. */
  15335. set: function (value) {
  15336. this._opaqueSortCompareFn = value;
  15337. if (value) {
  15338. this._renderOpaque = this.renderOpaqueSorted;
  15339. }
  15340. else {
  15341. this._renderOpaque = RenderingGroup.renderUnsorted;
  15342. }
  15343. },
  15344. enumerable: true,
  15345. configurable: true
  15346. });
  15347. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15348. /**
  15349. * Set the alpha test sort comparison function.
  15350. * If null the sub meshes will be render in the order they were created
  15351. */
  15352. set: function (value) {
  15353. this._alphaTestSortCompareFn = value;
  15354. if (value) {
  15355. this._renderAlphaTest = this.renderAlphaTestSorted;
  15356. }
  15357. else {
  15358. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15359. }
  15360. },
  15361. enumerable: true,
  15362. configurable: true
  15363. });
  15364. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15365. /**
  15366. * Set the transparent sort comparison function.
  15367. * If null the sub meshes will be render in the order they were created
  15368. */
  15369. set: function (value) {
  15370. if (value) {
  15371. this._transparentSortCompareFn = value;
  15372. }
  15373. else {
  15374. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15375. }
  15376. this._renderTransparent = this.renderTransparentSorted;
  15377. },
  15378. enumerable: true,
  15379. configurable: true
  15380. });
  15381. /**
  15382. * Render all the sub meshes contained in the group.
  15383. * @param customRenderFunction Used to override the default render behaviour of the group.
  15384. * @returns true if rendered some submeshes.
  15385. */
  15386. RenderingGroup.prototype.render = function (customRenderFunction) {
  15387. if (customRenderFunction) {
  15388. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15389. return true;
  15390. }
  15391. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15392. if (this.onBeforeTransparentRendering) {
  15393. this.onBeforeTransparentRendering();
  15394. }
  15395. return false;
  15396. }
  15397. var engine = this._scene.getEngine();
  15398. // Opaque
  15399. this._renderOpaque(this._opaqueSubMeshes);
  15400. // Alpha test
  15401. engine.setAlphaTesting(true);
  15402. this._renderAlphaTest(this._alphaTestSubMeshes);
  15403. engine.setAlphaTesting(false);
  15404. if (this.onBeforeTransparentRendering) {
  15405. this.onBeforeTransparentRendering();
  15406. }
  15407. // Transparent
  15408. this._renderTransparent(this._transparentSubMeshes);
  15409. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15410. return true;
  15411. };
  15412. /**
  15413. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15414. * @param subMeshes The submeshes to render
  15415. */
  15416. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15417. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15418. };
  15419. /**
  15420. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15421. * @param subMeshes The submeshes to render
  15422. */
  15423. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15424. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15425. };
  15426. /**
  15427. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15428. * @param subMeshes The submeshes to render
  15429. */
  15430. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15431. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15432. };
  15433. /**
  15434. * Renders the submeshes in a specified order.
  15435. * @param subMeshes The submeshes to sort before render
  15436. * @param sortCompareFn The comparison function use to sort
  15437. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15438. * @param transparent Specifies to activate blending if true
  15439. */
  15440. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15441. var subIndex = 0;
  15442. var subMesh;
  15443. for (; subIndex < subMeshes.length; subIndex++) {
  15444. subMesh = subMeshes.data[subIndex];
  15445. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15446. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15447. }
  15448. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15449. sortedArray.sort(sortCompareFn);
  15450. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15451. subMesh = sortedArray[subIndex];
  15452. subMesh.render(transparent);
  15453. }
  15454. };
  15455. /**
  15456. * Renders the submeshes in the order they were dispatched (no sort applied).
  15457. * @param subMeshes The submeshes to render
  15458. */
  15459. RenderingGroup.renderUnsorted = function (subMeshes) {
  15460. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15461. var submesh = subMeshes.data[subIndex];
  15462. submesh.render(false);
  15463. }
  15464. };
  15465. /**
  15466. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15467. * are rendered back to front if in the same alpha index.
  15468. *
  15469. * @param a The first submesh
  15470. * @param b The second submesh
  15471. * @returns The result of the comparison
  15472. */
  15473. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15474. // Alpha index first
  15475. if (a._alphaIndex > b._alphaIndex) {
  15476. return 1;
  15477. }
  15478. if (a._alphaIndex < b._alphaIndex) {
  15479. return -1;
  15480. }
  15481. // Then distance to camera
  15482. return RenderingGroup.backToFrontSortCompare(a, b);
  15483. };
  15484. /**
  15485. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15486. * are rendered back to front.
  15487. *
  15488. * @param a The first submesh
  15489. * @param b The second submesh
  15490. * @returns The result of the comparison
  15491. */
  15492. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15493. // Then distance to camera
  15494. if (a._distanceToCamera < b._distanceToCamera) {
  15495. return 1;
  15496. }
  15497. if (a._distanceToCamera > b._distanceToCamera) {
  15498. return -1;
  15499. }
  15500. return 0;
  15501. };
  15502. /**
  15503. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15504. * are rendered front to back (prevent overdraw).
  15505. *
  15506. * @param a The first submesh
  15507. * @param b The second submesh
  15508. * @returns The result of the comparison
  15509. */
  15510. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15511. // Then distance to camera
  15512. if (a._distanceToCamera < b._distanceToCamera) {
  15513. return -1;
  15514. }
  15515. if (a._distanceToCamera > b._distanceToCamera) {
  15516. return 1;
  15517. }
  15518. return 0;
  15519. };
  15520. /**
  15521. * Resets the different lists of submeshes to prepare a new frame.
  15522. */
  15523. RenderingGroup.prototype.prepare = function () {
  15524. this._opaqueSubMeshes.reset();
  15525. this._transparentSubMeshes.reset();
  15526. this._alphaTestSubMeshes.reset();
  15527. };
  15528. /**
  15529. * Inserts the submesh in its correct queue depending on its material.
  15530. * @param subMesh The submesh to dispatch
  15531. */
  15532. RenderingGroup.prototype.dispatch = function (subMesh) {
  15533. var material = subMesh.getMaterial();
  15534. var mesh = subMesh.getMesh();
  15535. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15536. this._transparentSubMeshes.push(subMesh);
  15537. }
  15538. else if (material.needAlphaTesting()) {
  15539. this._alphaTestSubMeshes.push(subMesh);
  15540. }
  15541. else {
  15542. this._opaqueSubMeshes.push(subMesh); // Opaque
  15543. }
  15544. };
  15545. return RenderingGroup;
  15546. }());
  15547. BABYLON.RenderingGroup = RenderingGroup;
  15548. })(BABYLON || (BABYLON = {}));
  15549. var BABYLON;
  15550. (function (BABYLON) {
  15551. var PointerEventTypes = (function () {
  15552. function PointerEventTypes() {
  15553. }
  15554. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  15555. get: function () {
  15556. return PointerEventTypes._POINTERDOWN;
  15557. },
  15558. enumerable: true,
  15559. configurable: true
  15560. });
  15561. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  15562. get: function () {
  15563. return PointerEventTypes._POINTERUP;
  15564. },
  15565. enumerable: true,
  15566. configurable: true
  15567. });
  15568. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  15569. get: function () {
  15570. return PointerEventTypes._POINTERMOVE;
  15571. },
  15572. enumerable: true,
  15573. configurable: true
  15574. });
  15575. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  15576. get: function () {
  15577. return PointerEventTypes._POINTERWHEEL;
  15578. },
  15579. enumerable: true,
  15580. configurable: true
  15581. });
  15582. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  15583. get: function () {
  15584. return PointerEventTypes._POINTERPICK;
  15585. },
  15586. enumerable: true,
  15587. configurable: true
  15588. });
  15589. PointerEventTypes._POINTERDOWN = 0x01;
  15590. PointerEventTypes._POINTERUP = 0x02;
  15591. PointerEventTypes._POINTERMOVE = 0x04;
  15592. PointerEventTypes._POINTERWHEEL = 0x08;
  15593. PointerEventTypes._POINTERPICK = 0x10;
  15594. return PointerEventTypes;
  15595. }());
  15596. BABYLON.PointerEventTypes = PointerEventTypes;
  15597. var PointerInfoBase = (function () {
  15598. function PointerInfoBase(type, event) {
  15599. this.type = type;
  15600. this.event = event;
  15601. }
  15602. return PointerInfoBase;
  15603. }());
  15604. BABYLON.PointerInfoBase = PointerInfoBase;
  15605. /**
  15606. * This class is used to store pointer related info for the onPrePointerObservable event.
  15607. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  15608. */
  15609. var PointerInfoPre = (function (_super) {
  15610. __extends(PointerInfoPre, _super);
  15611. function PointerInfoPre(type, event, localX, localY) {
  15612. _super.call(this, type, event);
  15613. this.skipOnPointerObservable = false;
  15614. this.localPosition = new BABYLON.Vector2(localX, localY);
  15615. }
  15616. return PointerInfoPre;
  15617. }(PointerInfoBase));
  15618. BABYLON.PointerInfoPre = PointerInfoPre;
  15619. /**
  15620. * This type contains all the data related to a pointer event in Babylon.js.
  15621. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  15622. */
  15623. var PointerInfo = (function (_super) {
  15624. __extends(PointerInfo, _super);
  15625. function PointerInfo(type, event, pickInfo) {
  15626. _super.call(this, type, event);
  15627. this.pickInfo = pickInfo;
  15628. }
  15629. return PointerInfo;
  15630. }(PointerInfoBase));
  15631. BABYLON.PointerInfo = PointerInfo;
  15632. /**
  15633. * Represents a scene to be rendered by the engine.
  15634. * @see http://doc.babylonjs.com/page.php?p=21911
  15635. */
  15636. var Scene = (function () {
  15637. /**
  15638. * @constructor
  15639. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  15640. */
  15641. function Scene(engine) {
  15642. // Members
  15643. this.autoClear = true;
  15644. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15645. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  15646. this.forceWireframe = false;
  15647. this.forcePointsCloud = false;
  15648. this.forceShowBoundingBoxes = false;
  15649. this.animationsEnabled = true;
  15650. this.constantlyUpdateMeshUnderPointer = false;
  15651. this.hoverCursor = "pointer";
  15652. // Events
  15653. /**
  15654. * An event triggered when the scene is disposed.
  15655. * @type {BABYLON.Observable}
  15656. */
  15657. this.onDisposeObservable = new BABYLON.Observable();
  15658. /**
  15659. * An event triggered before rendering the scene
  15660. * @type {BABYLON.Observable}
  15661. */
  15662. this.onBeforeRenderObservable = new BABYLON.Observable();
  15663. /**
  15664. * An event triggered after rendering the scene
  15665. * @type {BABYLON.Observable}
  15666. */
  15667. this.onAfterRenderObservable = new BABYLON.Observable();
  15668. /**
  15669. * An event triggered when the scene is ready
  15670. * @type {BABYLON.Observable}
  15671. */
  15672. this.onReadyObservable = new BABYLON.Observable();
  15673. /**
  15674. * An event triggered before rendering a camera
  15675. * @type {BABYLON.Observable}
  15676. */
  15677. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  15678. /**
  15679. * An event triggered after rendering a camera
  15680. * @type {BABYLON.Observable}
  15681. */
  15682. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  15683. /**
  15684. * An event triggered when a camera is created
  15685. * @type {BABYLON.Observable}
  15686. */
  15687. this.onNewCameraAddedObservable = new BABYLON.Observable();
  15688. /**
  15689. * An event triggered when a camera is removed
  15690. * @type {BABYLON.Observable}
  15691. */
  15692. this.onCameraRemovedObservable = new BABYLON.Observable();
  15693. /**
  15694. * An event triggered when a light is created
  15695. * @type {BABYLON.Observable}
  15696. */
  15697. this.onNewLightAddedObservable = new BABYLON.Observable();
  15698. /**
  15699. * An event triggered when a light is removed
  15700. * @type {BABYLON.Observable}
  15701. */
  15702. this.onLightRemovedObservable = new BABYLON.Observable();
  15703. /**
  15704. * An event triggered when a geometry is created
  15705. * @type {BABYLON.Observable}
  15706. */
  15707. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  15708. /**
  15709. * An event triggered when a geometry is removed
  15710. * @type {BABYLON.Observable}
  15711. */
  15712. this.onGeometryRemovedObservable = new BABYLON.Observable();
  15713. /**
  15714. * An event triggered when a mesh is created
  15715. * @type {BABYLON.Observable}
  15716. */
  15717. this.onNewMeshAddedObservable = new BABYLON.Observable();
  15718. /**
  15719. * An event triggered when a mesh is removed
  15720. * @type {BABYLON.Observable}
  15721. */
  15722. this.onMeshRemovedObservable = new BABYLON.Observable();
  15723. // Animations
  15724. this.animations = [];
  15725. /**
  15726. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  15727. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  15728. */
  15729. this.onPrePointerObservable = new BABYLON.Observable();
  15730. /**
  15731. * Observable event triggered each time an input event is received from the rendering canvas
  15732. */
  15733. this.onPointerObservable = new BABYLON.Observable();
  15734. 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
  15735. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  15736. this._startingPointerTime = 0;
  15737. // Fog
  15738. /**
  15739. * is fog enabled on this scene.
  15740. * @type {boolean}
  15741. */
  15742. this.fogEnabled = true;
  15743. this.fogMode = Scene.FOGMODE_NONE;
  15744. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  15745. this.fogDensity = 0.1;
  15746. this.fogStart = 0;
  15747. this.fogEnd = 1000.0;
  15748. // Lights
  15749. /**
  15750. * is shadow enabled on this scene.
  15751. * @type {boolean}
  15752. */
  15753. this.shadowsEnabled = true;
  15754. /**
  15755. * is light enabled on this scene.
  15756. * @type {boolean}
  15757. */
  15758. this.lightsEnabled = true;
  15759. /**
  15760. * All of the lights added to this scene.
  15761. * @see BABYLON.Light
  15762. * @type {BABYLON.Light[]}
  15763. */
  15764. this.lights = new Array();
  15765. // Cameras
  15766. /**
  15767. * All of the cameras added to this scene.
  15768. * @see BABYLON.Camera
  15769. * @type {BABYLON.Camera[]}
  15770. */
  15771. this.cameras = new Array();
  15772. this.activeCameras = new Array();
  15773. // Meshes
  15774. /**
  15775. * All of the (abstract) meshes added to this scene.
  15776. * @see BABYLON.AbstractMesh
  15777. * @type {BABYLON.AbstractMesh[]}
  15778. */
  15779. this.meshes = new Array();
  15780. // Geometries
  15781. this._geometries = new Array();
  15782. this.materials = new Array();
  15783. this.multiMaterials = new Array();
  15784. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  15785. // Textures
  15786. this.texturesEnabled = true;
  15787. this.textures = new Array();
  15788. // Particles
  15789. this.particlesEnabled = true;
  15790. this.particleSystems = new Array();
  15791. // Sprites
  15792. this.spritesEnabled = true;
  15793. this.spriteManagers = new Array();
  15794. // Layers
  15795. this.layers = new Array();
  15796. // Skeletons
  15797. this.skeletonsEnabled = true;
  15798. this.skeletons = new Array();
  15799. // Lens flares
  15800. this.lensFlaresEnabled = true;
  15801. this.lensFlareSystems = new Array();
  15802. // Collisions
  15803. this.collisionsEnabled = true;
  15804. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  15805. // Postprocesses
  15806. this.postProcessesEnabled = true;
  15807. // Customs render targets
  15808. this.renderTargetsEnabled = true;
  15809. this.dumpNextRenderTargets = false;
  15810. this.customRenderTargets = new Array();
  15811. // Imported meshes
  15812. this.importedMeshesFiles = new Array();
  15813. // Probes
  15814. this.probesEnabled = true;
  15815. this.reflectionProbes = new Array();
  15816. this._actionManagers = new Array();
  15817. this._meshesForIntersections = new BABYLON.SmartArray(256);
  15818. // Procedural textures
  15819. this.proceduralTexturesEnabled = true;
  15820. this._proceduralTextures = new Array();
  15821. this.soundTracks = new Array();
  15822. this._audioEnabled = true;
  15823. this._headphone = false;
  15824. // Performance counters
  15825. this._totalMeshesCounter = new BABYLON.PerfCounter();
  15826. this._totalLightsCounter = new BABYLON.PerfCounter();
  15827. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  15828. this._totalTexturesCounter = new BABYLON.PerfCounter();
  15829. this._totalVertices = new BABYLON.PerfCounter();
  15830. this._activeIndices = new BABYLON.PerfCounter();
  15831. this._activeParticles = new BABYLON.PerfCounter();
  15832. this._lastFrameDuration = new BABYLON.PerfCounter();
  15833. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  15834. this._renderTargetsDuration = new BABYLON.PerfCounter();
  15835. this._particlesDuration = new BABYLON.PerfCounter();
  15836. this._renderDuration = new BABYLON.PerfCounter();
  15837. this._spritesDuration = new BABYLON.PerfCounter();
  15838. this._activeBones = new BABYLON.PerfCounter();
  15839. this._renderId = 0;
  15840. this._executeWhenReadyTimeoutId = -1;
  15841. this._intermediateRendering = false;
  15842. this._toBeDisposed = new BABYLON.SmartArray(256);
  15843. this._pendingData = []; //ANY
  15844. this._activeMeshes = new BABYLON.SmartArray(256);
  15845. this._processedMaterials = new BABYLON.SmartArray(256);
  15846. this._renderTargets = new BABYLON.SmartArray(256);
  15847. this._activeParticleSystems = new BABYLON.SmartArray(256);
  15848. this._activeSkeletons = new BABYLON.SmartArray(32);
  15849. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  15850. this._activeAnimatables = new Array();
  15851. this._transformMatrix = BABYLON.Matrix.Zero();
  15852. this._edgesRenderers = new BABYLON.SmartArray(16);
  15853. this._uniqueIdCounter = 0;
  15854. this._engine = engine;
  15855. engine.scenes.push(this);
  15856. this._renderingManager = new BABYLON.RenderingManager(this);
  15857. this.postProcessManager = new BABYLON.PostProcessManager(this);
  15858. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  15859. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  15860. if (BABYLON.OutlineRenderer) {
  15861. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  15862. }
  15863. this.attachControl();
  15864. if (BABYLON.SoundTrack) {
  15865. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  15866. }
  15867. //simplification queue
  15868. if (BABYLON.SimplificationQueue) {
  15869. this.simplificationQueue = new BABYLON.SimplificationQueue();
  15870. }
  15871. //collision coordinator initialization. For now legacy per default.
  15872. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  15873. }
  15874. Object.defineProperty(Scene, "FOGMODE_NONE", {
  15875. get: function () {
  15876. return Scene._FOGMODE_NONE;
  15877. },
  15878. enumerable: true,
  15879. configurable: true
  15880. });
  15881. Object.defineProperty(Scene, "FOGMODE_EXP", {
  15882. get: function () {
  15883. return Scene._FOGMODE_EXP;
  15884. },
  15885. enumerable: true,
  15886. configurable: true
  15887. });
  15888. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  15889. get: function () {
  15890. return Scene._FOGMODE_EXP2;
  15891. },
  15892. enumerable: true,
  15893. configurable: true
  15894. });
  15895. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  15896. get: function () {
  15897. return Scene._FOGMODE_LINEAR;
  15898. },
  15899. enumerable: true,
  15900. configurable: true
  15901. });
  15902. Object.defineProperty(Scene.prototype, "onDispose", {
  15903. set: function (callback) {
  15904. if (this._onDisposeObserver) {
  15905. this.onDisposeObservable.remove(this._onDisposeObserver);
  15906. }
  15907. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15908. },
  15909. enumerable: true,
  15910. configurable: true
  15911. });
  15912. Object.defineProperty(Scene.prototype, "beforeRender", {
  15913. set: function (callback) {
  15914. if (this._onBeforeRenderObserver) {
  15915. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  15916. }
  15917. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  15918. },
  15919. enumerable: true,
  15920. configurable: true
  15921. });
  15922. Object.defineProperty(Scene.prototype, "afterRender", {
  15923. set: function (callback) {
  15924. if (this._onAfterRenderObserver) {
  15925. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  15926. }
  15927. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  15928. },
  15929. enumerable: true,
  15930. configurable: true
  15931. });
  15932. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  15933. set: function (callback) {
  15934. if (this._onBeforeCameraRenderObserver) {
  15935. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  15936. }
  15937. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  15938. },
  15939. enumerable: true,
  15940. configurable: true
  15941. });
  15942. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  15943. set: function (callback) {
  15944. if (this._onAfterCameraRenderObserver) {
  15945. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  15946. }
  15947. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  15948. },
  15949. enumerable: true,
  15950. configurable: true
  15951. });
  15952. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  15953. get: function () {
  15954. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  15955. },
  15956. enumerable: true,
  15957. configurable: true
  15958. });
  15959. Object.defineProperty(Scene.prototype, "debugLayer", {
  15960. // Properties
  15961. get: function () {
  15962. if (!this._debugLayer) {
  15963. this._debugLayer = new BABYLON.DebugLayer(this);
  15964. }
  15965. return this._debugLayer;
  15966. },
  15967. enumerable: true,
  15968. configurable: true
  15969. });
  15970. Object.defineProperty(Scene.prototype, "workerCollisions", {
  15971. get: function () {
  15972. return this._workerCollisions;
  15973. },
  15974. set: function (enabled) {
  15975. enabled = (enabled && !!Worker);
  15976. this._workerCollisions = enabled;
  15977. if (this.collisionCoordinator) {
  15978. this.collisionCoordinator.destroy();
  15979. }
  15980. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  15981. this.collisionCoordinator.init(this);
  15982. },
  15983. enumerable: true,
  15984. configurable: true
  15985. });
  15986. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  15987. get: function () {
  15988. return this._selectionOctree;
  15989. },
  15990. enumerable: true,
  15991. configurable: true
  15992. });
  15993. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  15994. /**
  15995. * The mesh that is currently under the pointer.
  15996. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  15997. */
  15998. get: function () {
  15999. return this._pointerOverMesh;
  16000. },
  16001. enumerable: true,
  16002. configurable: true
  16003. });
  16004. Object.defineProperty(Scene.prototype, "pointerX", {
  16005. /**
  16006. * Current on-screen X position of the pointer
  16007. * @return {number} X position of the pointer
  16008. */
  16009. get: function () {
  16010. return this._pointerX;
  16011. },
  16012. enumerable: true,
  16013. configurable: true
  16014. });
  16015. Object.defineProperty(Scene.prototype, "pointerY", {
  16016. /**
  16017. * Current on-screen Y position of the pointer
  16018. * @return {number} Y position of the pointer
  16019. */
  16020. get: function () {
  16021. return this._pointerY;
  16022. },
  16023. enumerable: true,
  16024. configurable: true
  16025. });
  16026. Scene.prototype.getCachedMaterial = function () {
  16027. return this._cachedMaterial;
  16028. };
  16029. Scene.prototype.getBoundingBoxRenderer = function () {
  16030. return this._boundingBoxRenderer;
  16031. };
  16032. Scene.prototype.getOutlineRenderer = function () {
  16033. return this._outlineRenderer;
  16034. };
  16035. Scene.prototype.getEngine = function () {
  16036. return this._engine;
  16037. };
  16038. Scene.prototype.getTotalVertices = function () {
  16039. return this._totalVertices.current;
  16040. };
  16041. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16042. get: function () {
  16043. return this._totalVertices;
  16044. },
  16045. enumerable: true,
  16046. configurable: true
  16047. });
  16048. Scene.prototype.getActiveIndices = function () {
  16049. return this._activeIndices.current;
  16050. };
  16051. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16052. get: function () {
  16053. return this._activeIndices;
  16054. },
  16055. enumerable: true,
  16056. configurable: true
  16057. });
  16058. Scene.prototype.getActiveParticles = function () {
  16059. return this._activeParticles.current;
  16060. };
  16061. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16062. get: function () {
  16063. return this._activeParticles;
  16064. },
  16065. enumerable: true,
  16066. configurable: true
  16067. });
  16068. Scene.prototype.getActiveBones = function () {
  16069. return this._activeBones.current;
  16070. };
  16071. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16072. get: function () {
  16073. return this._activeBones;
  16074. },
  16075. enumerable: true,
  16076. configurable: true
  16077. });
  16078. // Stats
  16079. Scene.prototype.getLastFrameDuration = function () {
  16080. return this._lastFrameDuration.current;
  16081. };
  16082. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16083. get: function () {
  16084. return this._lastFrameDuration;
  16085. },
  16086. enumerable: true,
  16087. configurable: true
  16088. });
  16089. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16090. return this._evaluateActiveMeshesDuration.current;
  16091. };
  16092. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16093. get: function () {
  16094. return this._evaluateActiveMeshesDuration;
  16095. },
  16096. enumerable: true,
  16097. configurable: true
  16098. });
  16099. Scene.prototype.getActiveMeshes = function () {
  16100. return this._activeMeshes;
  16101. };
  16102. Scene.prototype.getRenderTargetsDuration = function () {
  16103. return this._renderTargetsDuration.current;
  16104. };
  16105. Scene.prototype.getRenderDuration = function () {
  16106. return this._renderDuration.current;
  16107. };
  16108. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16109. get: function () {
  16110. return this._renderDuration;
  16111. },
  16112. enumerable: true,
  16113. configurable: true
  16114. });
  16115. Scene.prototype.getParticlesDuration = function () {
  16116. return this._particlesDuration.current;
  16117. };
  16118. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16119. get: function () {
  16120. return this._particlesDuration;
  16121. },
  16122. enumerable: true,
  16123. configurable: true
  16124. });
  16125. Scene.prototype.getSpritesDuration = function () {
  16126. return this._spritesDuration.current;
  16127. };
  16128. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16129. get: function () {
  16130. return this._spritesDuration;
  16131. },
  16132. enumerable: true,
  16133. configurable: true
  16134. });
  16135. Scene.prototype.getAnimationRatio = function () {
  16136. return this._animationRatio;
  16137. };
  16138. Scene.prototype.getRenderId = function () {
  16139. return this._renderId;
  16140. };
  16141. Scene.prototype.incrementRenderId = function () {
  16142. this._renderId++;
  16143. };
  16144. Scene.prototype._updatePointerPosition = function (evt) {
  16145. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16146. this._pointerX = evt.clientX - canvasRect.left;
  16147. this._pointerY = evt.clientY - canvasRect.top;
  16148. this._unTranslatedPointerX = this._pointerX;
  16149. this._unTranslatedPointerY = this._pointerY;
  16150. if (this.cameraToUseForPointers) {
  16151. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16152. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16153. }
  16154. };
  16155. // Pointers handling
  16156. /**
  16157. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16158. * @param attachUp defines if you want to attach events to pointerup
  16159. * @param attachDown defines if you want to attach events to pointerdown
  16160. * @param attachMove defines if you want to attach events to pointermove
  16161. */
  16162. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16163. var _this = this;
  16164. if (attachUp === void 0) { attachUp = true; }
  16165. if (attachDown === void 0) { attachDown = true; }
  16166. if (attachMove === void 0) { attachMove = true; }
  16167. var spritePredicate = function (sprite) {
  16168. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16169. };
  16170. this._onPointerMove = function (evt) {
  16171. _this._updatePointerPosition(evt);
  16172. // PreObservable support
  16173. if (_this.onPrePointerObservable.hasObservers()) {
  16174. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16175. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16176. _this.onPrePointerObservable.notifyObservers(pi, type);
  16177. if (pi.skipOnPointerObservable) {
  16178. return;
  16179. }
  16180. }
  16181. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16182. return;
  16183. }
  16184. var canvas = _this._engine.getRenderingCanvas();
  16185. if (!_this.pointerMovePredicate) {
  16186. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16187. }
  16188. // Meshes
  16189. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16190. if (pickResult.hit && pickResult.pickedMesh) {
  16191. _this.setPointerOverSprite(null);
  16192. _this.setPointerOverMesh(pickResult.pickedMesh);
  16193. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16194. canvas.style.cursor = _this.hoverCursor;
  16195. }
  16196. else {
  16197. canvas.style.cursor = "";
  16198. }
  16199. }
  16200. else {
  16201. _this.setPointerOverMesh(null);
  16202. // Sprites
  16203. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16204. if (pickResult.hit && pickResult.pickedSprite) {
  16205. canvas.style.cursor = _this.hoverCursor;
  16206. _this.setPointerOverSprite(pickResult.pickedSprite);
  16207. }
  16208. else {
  16209. _this.setPointerOverSprite(null);
  16210. // Restore pointer
  16211. canvas.style.cursor = "";
  16212. }
  16213. }
  16214. if (_this.onPointerMove) {
  16215. _this.onPointerMove(evt, pickResult);
  16216. }
  16217. if (_this.onPointerObservable.hasObservers()) {
  16218. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16219. var pi = new PointerInfo(type, evt, pickResult);
  16220. _this.onPointerObservable.notifyObservers(pi, type);
  16221. }
  16222. };
  16223. this._onPointerDown = function (evt) {
  16224. _this._updatePointerPosition(evt);
  16225. // PreObservable support
  16226. if (_this.onPrePointerObservable.hasObservers()) {
  16227. var type = PointerEventTypes.POINTERDOWN;
  16228. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16229. _this.onPrePointerObservable.notifyObservers(pi, type);
  16230. if (pi.skipOnPointerObservable) {
  16231. return;
  16232. }
  16233. }
  16234. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16235. return;
  16236. }
  16237. _this._startingPointerPosition.x = _this._pointerX;
  16238. _this._startingPointerPosition.y = _this._pointerY;
  16239. _this._startingPointerTime = new Date().getTime();
  16240. if (!_this.pointerDownPredicate) {
  16241. _this.pointerDownPredicate = function (mesh) {
  16242. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16243. };
  16244. }
  16245. // Meshes
  16246. _this._pickedDownMesh = null;
  16247. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16248. if (pickResult.hit && pickResult.pickedMesh) {
  16249. if (pickResult.pickedMesh.actionManager) {
  16250. _this._pickedDownMesh = pickResult.pickedMesh;
  16251. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16252. switch (evt.button) {
  16253. case 0:
  16254. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16255. break;
  16256. case 1:
  16257. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16258. break;
  16259. case 2:
  16260. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16261. break;
  16262. }
  16263. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16264. }
  16265. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16266. var that = _this;
  16267. window.setTimeout(function () {
  16268. 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);
  16269. if (pickResult.hit && pickResult.pickedMesh) {
  16270. if (pickResult.pickedMesh.actionManager) {
  16271. 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)) {
  16272. that._startingPointerTime = 0;
  16273. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16274. }
  16275. }
  16276. }
  16277. }, BABYLON.ActionManager.LongPressDelay);
  16278. }
  16279. }
  16280. }
  16281. if (_this.onPointerDown) {
  16282. _this.onPointerDown(evt, pickResult);
  16283. }
  16284. if (_this.onPointerObservable.hasObservers()) {
  16285. var type = PointerEventTypes.POINTERDOWN;
  16286. var pi = new PointerInfo(type, evt, pickResult);
  16287. _this.onPointerObservable.notifyObservers(pi, type);
  16288. }
  16289. // Sprites
  16290. _this._pickedDownSprite = null;
  16291. if (_this.spriteManagers.length > 0) {
  16292. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16293. if (pickResult.hit && pickResult.pickedSprite) {
  16294. if (pickResult.pickedSprite.actionManager) {
  16295. _this._pickedDownSprite = pickResult.pickedSprite;
  16296. switch (evt.button) {
  16297. case 0:
  16298. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16299. break;
  16300. case 1:
  16301. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16302. break;
  16303. case 2:
  16304. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16305. break;
  16306. }
  16307. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16308. }
  16309. }
  16310. }
  16311. };
  16312. this._onPointerUp = function (evt) {
  16313. _this._updatePointerPosition(evt);
  16314. // PreObservable support
  16315. if (_this.onPrePointerObservable.hasObservers()) {
  16316. var type = PointerEventTypes.POINTERUP;
  16317. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16318. _this.onPrePointerObservable.notifyObservers(pi, type);
  16319. if (pi.skipOnPointerObservable) {
  16320. return;
  16321. }
  16322. }
  16323. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16324. return;
  16325. }
  16326. if (!_this.pointerUpPredicate) {
  16327. _this.pointerUpPredicate = function (mesh) {
  16328. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16329. };
  16330. }
  16331. // Meshes
  16332. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16333. if (pickResult.hit && pickResult.pickedMesh) {
  16334. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16335. if (_this.onPointerPick) {
  16336. _this.onPointerPick(evt, pickResult);
  16337. }
  16338. if (_this.onPointerObservable.hasObservers()) {
  16339. var type = PointerEventTypes.POINTERPICK;
  16340. var pi = new PointerInfo(type, evt, pickResult);
  16341. _this.onPointerObservable.notifyObservers(pi, type);
  16342. }
  16343. }
  16344. if (pickResult.pickedMesh.actionManager) {
  16345. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16346. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16347. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16348. }
  16349. }
  16350. }
  16351. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16352. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16353. }
  16354. if (_this.onPointerUp) {
  16355. _this.onPointerUp(evt, pickResult);
  16356. }
  16357. if (_this.onPointerObservable.hasObservers()) {
  16358. var type = PointerEventTypes.POINTERUP;
  16359. var pi = new PointerInfo(type, evt, pickResult);
  16360. _this.onPointerObservable.notifyObservers(pi, type);
  16361. }
  16362. _this._startingPointerTime = 0;
  16363. // Sprites
  16364. if (_this.spriteManagers.length > 0) {
  16365. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16366. if (pickResult.hit && pickResult.pickedSprite) {
  16367. if (pickResult.pickedSprite.actionManager) {
  16368. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16369. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16370. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16371. }
  16372. }
  16373. }
  16374. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16375. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16376. }
  16377. }
  16378. };
  16379. this._onKeyDown = function (evt) {
  16380. if (_this.actionManager) {
  16381. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16382. }
  16383. };
  16384. this._onKeyUp = function (evt) {
  16385. if (_this.actionManager) {
  16386. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16387. }
  16388. };
  16389. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16390. var canvas = this._engine.getRenderingCanvas();
  16391. if (attachMove) {
  16392. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16393. // Wheel
  16394. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16395. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16396. }
  16397. if (attachDown) {
  16398. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16399. }
  16400. if (attachUp) {
  16401. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16402. }
  16403. canvas.tabIndex = 1;
  16404. canvas.addEventListener("keydown", this._onKeyDown, false);
  16405. canvas.addEventListener("keyup", this._onKeyUp, false);
  16406. };
  16407. Scene.prototype.detachControl = function () {
  16408. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16409. var canvas = this._engine.getRenderingCanvas();
  16410. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16411. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16412. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16413. // Wheel
  16414. canvas.removeEventListener('mousewheel', this._onPointerMove);
  16415. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  16416. canvas.removeEventListener("keydown", this._onKeyDown);
  16417. canvas.removeEventListener("keyup", this._onKeyUp);
  16418. };
  16419. // Ready
  16420. Scene.prototype.isReady = function () {
  16421. if (this._pendingData.length > 0) {
  16422. return false;
  16423. }
  16424. var index;
  16425. for (index = 0; index < this._geometries.length; index++) {
  16426. var geometry = this._geometries[index];
  16427. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  16428. return false;
  16429. }
  16430. }
  16431. for (index = 0; index < this.meshes.length; index++) {
  16432. var mesh = this.meshes[index];
  16433. if (!mesh.isReady()) {
  16434. return false;
  16435. }
  16436. var mat = mesh.material;
  16437. if (mat) {
  16438. if (!mat.isReady(mesh)) {
  16439. return false;
  16440. }
  16441. }
  16442. }
  16443. return true;
  16444. };
  16445. Scene.prototype.resetCachedMaterial = function () {
  16446. this._cachedMaterial = null;
  16447. };
  16448. Scene.prototype.registerBeforeRender = function (func) {
  16449. this.onBeforeRenderObservable.add(func);
  16450. };
  16451. Scene.prototype.unregisterBeforeRender = function (func) {
  16452. this.onBeforeRenderObservable.removeCallback(func);
  16453. };
  16454. Scene.prototype.registerAfterRender = function (func) {
  16455. this.onAfterRenderObservable.add(func);
  16456. };
  16457. Scene.prototype.unregisterAfterRender = function (func) {
  16458. this.onAfterRenderObservable.removeCallback(func);
  16459. };
  16460. Scene.prototype._addPendingData = function (data) {
  16461. this._pendingData.push(data);
  16462. };
  16463. Scene.prototype._removePendingData = function (data) {
  16464. var index = this._pendingData.indexOf(data);
  16465. if (index !== -1) {
  16466. this._pendingData.splice(index, 1);
  16467. }
  16468. };
  16469. Scene.prototype.getWaitingItemsCount = function () {
  16470. return this._pendingData.length;
  16471. };
  16472. /**
  16473. * Registers a function to be executed when the scene is ready.
  16474. * @param {Function} func - the function to be executed.
  16475. */
  16476. Scene.prototype.executeWhenReady = function (func) {
  16477. var _this = this;
  16478. this.onReadyObservable.add(func);
  16479. if (this._executeWhenReadyTimeoutId !== -1) {
  16480. return;
  16481. }
  16482. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16483. _this._checkIsReady();
  16484. }, 150);
  16485. };
  16486. Scene.prototype._checkIsReady = function () {
  16487. var _this = this;
  16488. if (this.isReady()) {
  16489. this.onReadyObservable.notifyObservers(this);
  16490. this.onReadyObservable.clear();
  16491. this._executeWhenReadyTimeoutId = -1;
  16492. return;
  16493. }
  16494. this._executeWhenReadyTimeoutId = setTimeout(function () {
  16495. _this._checkIsReady();
  16496. }, 150);
  16497. };
  16498. // Animations
  16499. /**
  16500. * Will start the animation sequence of a given target
  16501. * @param target - the target
  16502. * @param {number} from - from which frame should animation start
  16503. * @param {number} to - till which frame should animation run.
  16504. * @param {boolean} [loop] - should the animation loop
  16505. * @param {number} [speedRatio] - the speed in which to run the animation
  16506. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  16507. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  16508. * @return {BABYLON.Animatable} the animatable object created for this animation
  16509. * @see BABYLON.Animatable
  16510. * @see http://doc.babylonjs.com/page.php?p=22081
  16511. */
  16512. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  16513. if (speedRatio === void 0) { speedRatio = 1.0; }
  16514. this.stopAnimation(target);
  16515. if (!animatable) {
  16516. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  16517. }
  16518. // Local animations
  16519. if (target.animations) {
  16520. animatable.appendAnimations(target, target.animations);
  16521. }
  16522. // Children animations
  16523. if (target.getAnimatables) {
  16524. var animatables = target.getAnimatables();
  16525. for (var index = 0; index < animatables.length; index++) {
  16526. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  16527. }
  16528. }
  16529. animatable.reset();
  16530. return animatable;
  16531. };
  16532. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  16533. if (speedRatio === undefined) {
  16534. speedRatio = 1.0;
  16535. }
  16536. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  16537. return animatable;
  16538. };
  16539. Scene.prototype.getAnimatableByTarget = function (target) {
  16540. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16541. if (this._activeAnimatables[index].target === target) {
  16542. return this._activeAnimatables[index];
  16543. }
  16544. }
  16545. return null;
  16546. };
  16547. Object.defineProperty(Scene.prototype, "Animatables", {
  16548. get: function () {
  16549. return this._activeAnimatables;
  16550. },
  16551. enumerable: true,
  16552. configurable: true
  16553. });
  16554. /**
  16555. * Will stop the animation of the given target
  16556. * @param target - the target
  16557. * @see beginAnimation
  16558. */
  16559. Scene.prototype.stopAnimation = function (target) {
  16560. var animatable = this.getAnimatableByTarget(target);
  16561. if (animatable) {
  16562. animatable.stop();
  16563. }
  16564. };
  16565. Scene.prototype._animate = function () {
  16566. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  16567. return;
  16568. }
  16569. if (!this._animationStartDate) {
  16570. if (this._pendingData.length > 0) {
  16571. return;
  16572. }
  16573. this._animationStartDate = BABYLON.Tools.Now;
  16574. }
  16575. // Getting time
  16576. var now = BABYLON.Tools.Now;
  16577. var delay = now - this._animationStartDate;
  16578. for (var index = 0; index < this._activeAnimatables.length; index++) {
  16579. this._activeAnimatables[index]._animate(delay);
  16580. }
  16581. };
  16582. // Matrix
  16583. Scene.prototype.getViewMatrix = function () {
  16584. return this._viewMatrix;
  16585. };
  16586. Scene.prototype.getProjectionMatrix = function () {
  16587. return this._projectionMatrix;
  16588. };
  16589. Scene.prototype.getTransformMatrix = function () {
  16590. return this._transformMatrix;
  16591. };
  16592. Scene.prototype.setTransformMatrix = function (view, projection) {
  16593. this._viewMatrix = view;
  16594. this._projectionMatrix = projection;
  16595. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  16596. // Update frustum
  16597. if (!this._frustumPlanes) {
  16598. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  16599. }
  16600. else {
  16601. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  16602. }
  16603. };
  16604. // Methods
  16605. Scene.prototype.addMesh = function (newMesh) {
  16606. newMesh.uniqueId = this._uniqueIdCounter++;
  16607. var position = this.meshes.push(newMesh);
  16608. //notify the collision coordinator
  16609. this.collisionCoordinator.onMeshAdded(newMesh);
  16610. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  16611. };
  16612. Scene.prototype.removeMesh = function (toRemove) {
  16613. var index = this.meshes.indexOf(toRemove);
  16614. if (index !== -1) {
  16615. // Remove from the scene if mesh found
  16616. this.meshes.splice(index, 1);
  16617. }
  16618. //notify the collision coordinator
  16619. this.collisionCoordinator.onMeshRemoved(toRemove);
  16620. this.onMeshRemovedObservable.notifyObservers(toRemove);
  16621. return index;
  16622. };
  16623. Scene.prototype.removeSkeleton = function (toRemove) {
  16624. var index = this.skeletons.indexOf(toRemove);
  16625. if (index !== -1) {
  16626. // Remove from the scene if mesh found
  16627. this.skeletons.splice(index, 1);
  16628. }
  16629. return index;
  16630. };
  16631. Scene.prototype.removeLight = function (toRemove) {
  16632. var index = this.lights.indexOf(toRemove);
  16633. if (index !== -1) {
  16634. // Remove from the scene if mesh found
  16635. this.lights.splice(index, 1);
  16636. }
  16637. this.onLightRemovedObservable.notifyObservers(toRemove);
  16638. return index;
  16639. };
  16640. Scene.prototype.removeCamera = function (toRemove) {
  16641. var index = this.cameras.indexOf(toRemove);
  16642. if (index !== -1) {
  16643. // Remove from the scene if mesh found
  16644. this.cameras.splice(index, 1);
  16645. }
  16646. // Remove from activeCameras
  16647. var index2 = this.activeCameras.indexOf(toRemove);
  16648. if (index2 !== -1) {
  16649. // Remove from the scene if mesh found
  16650. this.activeCameras.splice(index2, 1);
  16651. }
  16652. // Reset the activeCamera
  16653. if (this.activeCamera === toRemove) {
  16654. if (this.cameras.length > 0) {
  16655. this.activeCamera = this.cameras[0];
  16656. }
  16657. else {
  16658. this.activeCamera = null;
  16659. }
  16660. }
  16661. this.onCameraRemovedObservable.notifyObservers(toRemove);
  16662. return index;
  16663. };
  16664. Scene.prototype.addLight = function (newLight) {
  16665. newLight.uniqueId = this._uniqueIdCounter++;
  16666. var position = this.lights.push(newLight);
  16667. this.onNewLightAddedObservable.notifyObservers(newLight);
  16668. };
  16669. Scene.prototype.addCamera = function (newCamera) {
  16670. newCamera.uniqueId = this._uniqueIdCounter++;
  16671. var position = this.cameras.push(newCamera);
  16672. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  16673. };
  16674. /**
  16675. * Switch active camera
  16676. * @param {Camera} newCamera - new active camera
  16677. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  16678. */
  16679. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  16680. if (attachControl === void 0) { attachControl = true; }
  16681. var canvas = this._engine.getRenderingCanvas();
  16682. this.activeCamera.detachControl(canvas);
  16683. this.activeCamera = newCamera;
  16684. if (attachControl) {
  16685. newCamera.attachControl(canvas);
  16686. }
  16687. };
  16688. /**
  16689. * sets the active camera of the scene using its ID
  16690. * @param {string} id - the camera's ID
  16691. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16692. * @see activeCamera
  16693. */
  16694. Scene.prototype.setActiveCameraByID = function (id) {
  16695. var camera = this.getCameraByID(id);
  16696. if (camera) {
  16697. this.activeCamera = camera;
  16698. return camera;
  16699. }
  16700. return null;
  16701. };
  16702. /**
  16703. * sets the active camera of the scene using its name
  16704. * @param {string} name - the camera's name
  16705. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  16706. * @see activeCamera
  16707. */
  16708. Scene.prototype.setActiveCameraByName = function (name) {
  16709. var camera = this.getCameraByName(name);
  16710. if (camera) {
  16711. this.activeCamera = camera;
  16712. return camera;
  16713. }
  16714. return null;
  16715. };
  16716. /**
  16717. * get a material using its id
  16718. * @param {string} the material's ID
  16719. * @return {BABYLON.Material|null} the material or null if none found.
  16720. */
  16721. Scene.prototype.getMaterialByID = function (id) {
  16722. for (var index = 0; index < this.materials.length; index++) {
  16723. if (this.materials[index].id === id) {
  16724. return this.materials[index];
  16725. }
  16726. }
  16727. return null;
  16728. };
  16729. /**
  16730. * get a material using its name
  16731. * @param {string} the material's name
  16732. * @return {BABYLON.Material|null} the material or null if none found.
  16733. */
  16734. Scene.prototype.getMaterialByName = function (name) {
  16735. for (var index = 0; index < this.materials.length; index++) {
  16736. if (this.materials[index].name === name) {
  16737. return this.materials[index];
  16738. }
  16739. }
  16740. return null;
  16741. };
  16742. Scene.prototype.getLensFlareSystemByName = function (name) {
  16743. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16744. if (this.lensFlareSystems[index].name === name) {
  16745. return this.lensFlareSystems[index];
  16746. }
  16747. }
  16748. return null;
  16749. };
  16750. Scene.prototype.getLensFlareSystemByID = function (id) {
  16751. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  16752. if (this.lensFlareSystems[index].id === id) {
  16753. return this.lensFlareSystems[index];
  16754. }
  16755. }
  16756. return null;
  16757. };
  16758. Scene.prototype.getCameraByID = function (id) {
  16759. for (var index = 0; index < this.cameras.length; index++) {
  16760. if (this.cameras[index].id === id) {
  16761. return this.cameras[index];
  16762. }
  16763. }
  16764. return null;
  16765. };
  16766. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  16767. for (var index = 0; index < this.cameras.length; index++) {
  16768. if (this.cameras[index].uniqueId === uniqueId) {
  16769. return this.cameras[index];
  16770. }
  16771. }
  16772. return null;
  16773. };
  16774. /**
  16775. * get a camera using its name
  16776. * @param {string} the camera's name
  16777. * @return {BABYLON.Camera|null} the camera or null if none found.
  16778. */
  16779. Scene.prototype.getCameraByName = function (name) {
  16780. for (var index = 0; index < this.cameras.length; index++) {
  16781. if (this.cameras[index].name === name) {
  16782. return this.cameras[index];
  16783. }
  16784. }
  16785. return null;
  16786. };
  16787. /**
  16788. * get a bone using its id
  16789. * @param {string} the bone's id
  16790. * @return {BABYLON.Bone|null} the bone or null if not found
  16791. */
  16792. Scene.prototype.getBoneByID = function (id) {
  16793. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16794. var skeleton = this.skeletons[skeletonIndex];
  16795. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16796. if (skeleton.bones[boneIndex].id === id) {
  16797. return skeleton.bones[boneIndex];
  16798. }
  16799. }
  16800. }
  16801. return null;
  16802. };
  16803. /**
  16804. * get a bone using its id
  16805. * @param {string} the bone's name
  16806. * @return {BABYLON.Bone|null} the bone or null if not found
  16807. */
  16808. Scene.prototype.getBoneByName = function (name) {
  16809. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  16810. var skeleton = this.skeletons[skeletonIndex];
  16811. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  16812. if (skeleton.bones[boneIndex].name === name) {
  16813. return skeleton.bones[boneIndex];
  16814. }
  16815. }
  16816. }
  16817. return null;
  16818. };
  16819. /**
  16820. * get a light node using its name
  16821. * @param {string} the light's name
  16822. * @return {BABYLON.Light|null} the light or null if none found.
  16823. */
  16824. Scene.prototype.getLightByName = function (name) {
  16825. for (var index = 0; index < this.lights.length; index++) {
  16826. if (this.lights[index].name === name) {
  16827. return this.lights[index];
  16828. }
  16829. }
  16830. return null;
  16831. };
  16832. /**
  16833. * get a light node using its ID
  16834. * @param {string} the light's id
  16835. * @return {BABYLON.Light|null} the light or null if none found.
  16836. */
  16837. Scene.prototype.getLightByID = function (id) {
  16838. for (var index = 0; index < this.lights.length; index++) {
  16839. if (this.lights[index].id === id) {
  16840. return this.lights[index];
  16841. }
  16842. }
  16843. return null;
  16844. };
  16845. /**
  16846. * get a light node using its scene-generated unique ID
  16847. * @param {number} the light's unique id
  16848. * @return {BABYLON.Light|null} the light or null if none found.
  16849. */
  16850. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  16851. for (var index = 0; index < this.lights.length; index++) {
  16852. if (this.lights[index].uniqueId === uniqueId) {
  16853. return this.lights[index];
  16854. }
  16855. }
  16856. return null;
  16857. };
  16858. /**
  16859. * get a particle system by id
  16860. * @param id {number} the particle system id
  16861. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  16862. */
  16863. Scene.prototype.getParticleSystemByID = function (id) {
  16864. for (var index = 0; index < this.particleSystems.length; index++) {
  16865. if (this.particleSystems[index].id === id) {
  16866. return this.particleSystems[index];
  16867. }
  16868. }
  16869. return null;
  16870. };
  16871. /**
  16872. * get a geometry using its ID
  16873. * @param {string} the geometry's id
  16874. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  16875. */
  16876. Scene.prototype.getGeometryByID = function (id) {
  16877. for (var index = 0; index < this._geometries.length; index++) {
  16878. if (this._geometries[index].id === id) {
  16879. return this._geometries[index];
  16880. }
  16881. }
  16882. return null;
  16883. };
  16884. /**
  16885. * add a new geometry to this scene.
  16886. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  16887. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  16888. * @return {boolean} was the geometry added or not
  16889. */
  16890. Scene.prototype.pushGeometry = function (geometry, force) {
  16891. if (!force && this.getGeometryByID(geometry.id)) {
  16892. return false;
  16893. }
  16894. this._geometries.push(geometry);
  16895. //notify the collision coordinator
  16896. this.collisionCoordinator.onGeometryAdded(geometry);
  16897. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  16898. return true;
  16899. };
  16900. /**
  16901. * Removes an existing geometry
  16902. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  16903. * @return {boolean} was the geometry removed or not
  16904. */
  16905. Scene.prototype.removeGeometry = function (geometry) {
  16906. var index = this._geometries.indexOf(geometry);
  16907. if (index > -1) {
  16908. this._geometries.splice(index, 1);
  16909. //notify the collision coordinator
  16910. this.collisionCoordinator.onGeometryDeleted(geometry);
  16911. this.onGeometryRemovedObservable.notifyObservers(geometry);
  16912. return true;
  16913. }
  16914. return false;
  16915. };
  16916. Scene.prototype.getGeometries = function () {
  16917. return this._geometries;
  16918. };
  16919. /**
  16920. * Get the first added mesh found of a given ID
  16921. * @param {string} id - the id to search for
  16922. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16923. */
  16924. Scene.prototype.getMeshByID = function (id) {
  16925. for (var index = 0; index < this.meshes.length; index++) {
  16926. if (this.meshes[index].id === id) {
  16927. return this.meshes[index];
  16928. }
  16929. }
  16930. return null;
  16931. };
  16932. Scene.prototype.getMeshesByID = function (id) {
  16933. return this.meshes.filter(function (m) {
  16934. return m.id === id;
  16935. });
  16936. };
  16937. /**
  16938. * Get a mesh with its auto-generated unique id
  16939. * @param {number} uniqueId - the unique id to search for
  16940. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16941. */
  16942. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  16943. for (var index = 0; index < this.meshes.length; index++) {
  16944. if (this.meshes[index].uniqueId === uniqueId) {
  16945. return this.meshes[index];
  16946. }
  16947. }
  16948. return null;
  16949. };
  16950. /**
  16951. * Get a the last added mesh found of a given ID
  16952. * @param {string} id - the id to search for
  16953. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  16954. */
  16955. Scene.prototype.getLastMeshByID = function (id) {
  16956. for (var index = this.meshes.length - 1; index >= 0; index--) {
  16957. if (this.meshes[index].id === id) {
  16958. return this.meshes[index];
  16959. }
  16960. }
  16961. return null;
  16962. };
  16963. /**
  16964. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  16965. * @param {string} id - the id to search for
  16966. * @return {BABYLON.Node|null} the node found or null if not found at all.
  16967. */
  16968. Scene.prototype.getLastEntryByID = function (id) {
  16969. var index;
  16970. for (index = this.meshes.length - 1; index >= 0; index--) {
  16971. if (this.meshes[index].id === id) {
  16972. return this.meshes[index];
  16973. }
  16974. }
  16975. for (index = this.cameras.length - 1; index >= 0; index--) {
  16976. if (this.cameras[index].id === id) {
  16977. return this.cameras[index];
  16978. }
  16979. }
  16980. for (index = this.lights.length - 1; index >= 0; index--) {
  16981. if (this.lights[index].id === id) {
  16982. return this.lights[index];
  16983. }
  16984. }
  16985. return null;
  16986. };
  16987. Scene.prototype.getNodeByID = function (id) {
  16988. var mesh = this.getMeshByID(id);
  16989. if (mesh) {
  16990. return mesh;
  16991. }
  16992. var light = this.getLightByID(id);
  16993. if (light) {
  16994. return light;
  16995. }
  16996. var camera = this.getCameraByID(id);
  16997. if (camera) {
  16998. return camera;
  16999. }
  17000. var bone = this.getBoneByID(id);
  17001. return bone;
  17002. };
  17003. Scene.prototype.getNodeByName = function (name) {
  17004. var mesh = this.getMeshByName(name);
  17005. if (mesh) {
  17006. return mesh;
  17007. }
  17008. var light = this.getLightByName(name);
  17009. if (light) {
  17010. return light;
  17011. }
  17012. var camera = this.getCameraByName(name);
  17013. if (camera) {
  17014. return camera;
  17015. }
  17016. var bone = this.getBoneByName(name);
  17017. return bone;
  17018. };
  17019. Scene.prototype.getMeshByName = function (name) {
  17020. for (var index = 0; index < this.meshes.length; index++) {
  17021. if (this.meshes[index].name === name) {
  17022. return this.meshes[index];
  17023. }
  17024. }
  17025. return null;
  17026. };
  17027. Scene.prototype.getSoundByName = function (name) {
  17028. var index;
  17029. if (BABYLON.AudioEngine) {
  17030. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17031. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17032. return this.mainSoundTrack.soundCollection[index];
  17033. }
  17034. }
  17035. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17036. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17037. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17038. return this.soundTracks[sdIndex].soundCollection[index];
  17039. }
  17040. }
  17041. }
  17042. }
  17043. return null;
  17044. };
  17045. Scene.prototype.getLastSkeletonByID = function (id) {
  17046. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17047. if (this.skeletons[index].id === id) {
  17048. return this.skeletons[index];
  17049. }
  17050. }
  17051. return null;
  17052. };
  17053. Scene.prototype.getSkeletonById = function (id) {
  17054. for (var index = 0; index < this.skeletons.length; index++) {
  17055. if (this.skeletons[index].id === id) {
  17056. return this.skeletons[index];
  17057. }
  17058. }
  17059. return null;
  17060. };
  17061. Scene.prototype.getSkeletonByName = function (name) {
  17062. for (var index = 0; index < this.skeletons.length; index++) {
  17063. if (this.skeletons[index].name === name) {
  17064. return this.skeletons[index];
  17065. }
  17066. }
  17067. return null;
  17068. };
  17069. Scene.prototype.isActiveMesh = function (mesh) {
  17070. return (this._activeMeshes.indexOf(mesh) !== -1);
  17071. };
  17072. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17073. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17074. var material = subMesh.getMaterial();
  17075. if (mesh.showSubMeshesBoundingBox) {
  17076. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17077. }
  17078. if (material) {
  17079. // Render targets
  17080. if (material.getRenderTargetTextures) {
  17081. if (this._processedMaterials.indexOf(material) === -1) {
  17082. this._processedMaterials.push(material);
  17083. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17084. }
  17085. }
  17086. // Dispatch
  17087. this._activeIndices.addCount(subMesh.indexCount, false);
  17088. this._renderingManager.dispatch(subMesh);
  17089. }
  17090. }
  17091. };
  17092. Scene.prototype._isInIntermediateRendering = function () {
  17093. return this._intermediateRendering;
  17094. };
  17095. Scene.prototype._evaluateActiveMeshes = function () {
  17096. this.activeCamera._activeMeshes.reset();
  17097. this._activeMeshes.reset();
  17098. this._renderingManager.reset();
  17099. this._processedMaterials.reset();
  17100. this._activeParticleSystems.reset();
  17101. this._activeSkeletons.reset();
  17102. this._softwareSkinnedMeshes.reset();
  17103. this._boundingBoxRenderer.reset();
  17104. this._edgesRenderers.reset();
  17105. // Meshes
  17106. var meshes;
  17107. var len;
  17108. if (this._selectionOctree) {
  17109. var selection = this._selectionOctree.select(this._frustumPlanes);
  17110. meshes = selection.data;
  17111. len = selection.length;
  17112. }
  17113. else {
  17114. len = this.meshes.length;
  17115. meshes = this.meshes;
  17116. }
  17117. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17118. var mesh = meshes[meshIndex];
  17119. if (mesh.isBlocked) {
  17120. continue;
  17121. }
  17122. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17123. if (!mesh.isReady() || !mesh.isEnabled()) {
  17124. continue;
  17125. }
  17126. mesh.computeWorldMatrix();
  17127. // Intersections
  17128. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17129. this._meshesForIntersections.pushNoDuplicate(mesh);
  17130. }
  17131. // Switch to current LOD
  17132. var meshLOD = mesh.getLOD(this.activeCamera);
  17133. if (!meshLOD) {
  17134. continue;
  17135. }
  17136. mesh._preActivate();
  17137. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17138. this._activeMeshes.push(mesh);
  17139. this.activeCamera._activeMeshes.push(mesh);
  17140. mesh._activate(this._renderId);
  17141. this._activeMesh(mesh, meshLOD);
  17142. }
  17143. }
  17144. // Particle systems
  17145. this._particlesDuration.beginMonitoring();
  17146. var beforeParticlesDate = BABYLON.Tools.Now;
  17147. if (this.particlesEnabled) {
  17148. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17149. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17150. var particleSystem = this.particleSystems[particleIndex];
  17151. if (!particleSystem.isStarted()) {
  17152. continue;
  17153. }
  17154. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17155. this._activeParticleSystems.push(particleSystem);
  17156. particleSystem.animate();
  17157. }
  17158. }
  17159. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17160. }
  17161. this._particlesDuration.endMonitoring(false);
  17162. };
  17163. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17164. if (mesh.skeleton && this.skeletonsEnabled) {
  17165. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17166. mesh.skeleton.prepare();
  17167. }
  17168. if (!mesh.computeBonesUsingShaders) {
  17169. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17170. }
  17171. }
  17172. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17173. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17174. }
  17175. if (sourceMesh._edgesRenderer) {
  17176. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17177. }
  17178. if (mesh && mesh.subMeshes) {
  17179. // Submeshes Octrees
  17180. var len;
  17181. var subMeshes;
  17182. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17183. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17184. len = intersections.length;
  17185. subMeshes = intersections.data;
  17186. }
  17187. else {
  17188. subMeshes = mesh.subMeshes;
  17189. len = subMeshes.length;
  17190. }
  17191. for (var subIndex = 0; subIndex < len; subIndex++) {
  17192. var subMesh = subMeshes[subIndex];
  17193. this._evaluateSubMesh(subMesh, mesh);
  17194. }
  17195. }
  17196. };
  17197. Scene.prototype.updateTransformMatrix = function (force) {
  17198. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17199. };
  17200. Scene.prototype._renderForCamera = function (camera) {
  17201. var engine = this._engine;
  17202. var startTime = BABYLON.Tools.Now;
  17203. this.activeCamera = camera;
  17204. if (!this.activeCamera)
  17205. throw new Error("Active camera not set");
  17206. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17207. // Viewport
  17208. engine.setViewport(this.activeCamera.viewport);
  17209. // Camera
  17210. this.resetCachedMaterial();
  17211. this._renderId++;
  17212. this.updateTransformMatrix();
  17213. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17214. // Meshes
  17215. this._evaluateActiveMeshesDuration.beginMonitoring();
  17216. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17217. this._evaluateActiveMeshes();
  17218. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17219. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17220. // Software skinning
  17221. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17222. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17223. mesh.applySkeleton(mesh.skeleton);
  17224. }
  17225. // Render targets
  17226. this._renderTargetsDuration.beginMonitoring();
  17227. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17228. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17229. this._intermediateRendering = true;
  17230. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17231. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17232. var renderTarget = this._renderTargets.data[renderIndex];
  17233. if (renderTarget._shouldRender()) {
  17234. this._renderId++;
  17235. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17236. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17237. }
  17238. }
  17239. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17240. this._intermediateRendering = false;
  17241. this._renderId++;
  17242. engine.restoreDefaultFramebuffer(); // Restore back buffer
  17243. }
  17244. this._renderTargetsDuration.endMonitoring(false);
  17245. // Prepare Frame
  17246. this.postProcessManager._prepareFrame();
  17247. this._renderDuration.beginMonitoring();
  17248. // Backgrounds
  17249. var layerIndex;
  17250. var layer;
  17251. if (this.layers.length) {
  17252. engine.setDepthBuffer(false);
  17253. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17254. layer = this.layers[layerIndex];
  17255. if (layer.isBackground) {
  17256. layer.render();
  17257. }
  17258. }
  17259. engine.setDepthBuffer(true);
  17260. }
  17261. // Render
  17262. BABYLON.Tools.StartPerformanceCounter("Main render");
  17263. this._renderingManager.render(null, null, true, true);
  17264. BABYLON.Tools.EndPerformanceCounter("Main render");
  17265. // Bounding boxes
  17266. this._boundingBoxRenderer.render();
  17267. // Edges
  17268. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17269. this._edgesRenderers.data[edgesRendererIndex].render();
  17270. }
  17271. // Lens flares
  17272. if (this.lensFlaresEnabled) {
  17273. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17274. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17275. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17276. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17277. lensFlareSystem.render();
  17278. }
  17279. }
  17280. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17281. }
  17282. // Foregrounds
  17283. if (this.layers.length) {
  17284. engine.setDepthBuffer(false);
  17285. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17286. layer = this.layers[layerIndex];
  17287. if (!layer.isBackground) {
  17288. layer.render();
  17289. }
  17290. }
  17291. engine.setDepthBuffer(true);
  17292. }
  17293. this._renderDuration.endMonitoring(false);
  17294. // Finalize frame
  17295. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17296. // Update camera
  17297. this.activeCamera._updateFromScene();
  17298. // Reset some special arrays
  17299. this._renderTargets.reset();
  17300. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17301. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17302. };
  17303. Scene.prototype._processSubCameras = function (camera) {
  17304. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17305. this._renderForCamera(camera);
  17306. return;
  17307. }
  17308. // rig cameras
  17309. for (var index = 0; index < camera._rigCameras.length; index++) {
  17310. this._renderForCamera(camera._rigCameras[index]);
  17311. }
  17312. this.activeCamera = camera;
  17313. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17314. // Update camera
  17315. this.activeCamera._updateFromScene();
  17316. };
  17317. Scene.prototype._checkIntersections = function () {
  17318. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  17319. var sourceMesh = this._meshesForIntersections.data[index];
  17320. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  17321. var action = sourceMesh.actionManager.actions[actionIndex];
  17322. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17323. var parameters = action.getTriggerParameter();
  17324. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  17325. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  17326. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  17327. if (areIntersecting && currentIntersectionInProgress === -1) {
  17328. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  17329. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17330. sourceMesh._intersectionsInProgress.push(otherMesh);
  17331. }
  17332. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17333. sourceMesh._intersectionsInProgress.push(otherMesh);
  17334. }
  17335. }
  17336. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  17337. //They intersected, and now they don't.
  17338. //is this trigger an exit trigger? execute an event.
  17339. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17340. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  17341. }
  17342. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  17343. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  17344. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  17345. }
  17346. }
  17347. }
  17348. }
  17349. }
  17350. };
  17351. Scene.prototype.render = function () {
  17352. this._lastFrameDuration.beginMonitoring();
  17353. this._particlesDuration.fetchNewFrame();
  17354. this._spritesDuration.fetchNewFrame();
  17355. this._activeParticles.fetchNewFrame();
  17356. this._renderDuration.fetchNewFrame();
  17357. this._renderTargetsDuration.fetchNewFrame();
  17358. this._evaluateActiveMeshesDuration.fetchNewFrame();
  17359. this._totalVertices.fetchNewFrame();
  17360. this._activeIndices.fetchNewFrame();
  17361. this._activeBones.fetchNewFrame();
  17362. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  17363. this._meshesForIntersections.reset();
  17364. this.resetCachedMaterial();
  17365. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  17366. // Actions
  17367. if (this.actionManager) {
  17368. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  17369. }
  17370. //Simplification Queue
  17371. if (this.simplificationQueue && !this.simplificationQueue.running) {
  17372. this.simplificationQueue.executeNext();
  17373. }
  17374. // Animations
  17375. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  17376. this._animationRatio = deltaTime * (60.0 / 1000.0);
  17377. this._animate();
  17378. // Physics
  17379. if (this._physicsEngine) {
  17380. BABYLON.Tools.StartPerformanceCounter("Physics");
  17381. this._physicsEngine._step(deltaTime / 1000.0);
  17382. BABYLON.Tools.EndPerformanceCounter("Physics");
  17383. }
  17384. // Before render
  17385. this.onBeforeRenderObservable.notifyObservers(this);
  17386. // Customs render targets
  17387. this._renderTargetsDuration.beginMonitoring();
  17388. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17389. var engine = this.getEngine();
  17390. var currentActiveCamera = this.activeCamera;
  17391. if (this.renderTargetsEnabled) {
  17392. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17393. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  17394. var renderTarget = this.customRenderTargets[customIndex];
  17395. if (renderTarget._shouldRender()) {
  17396. this._renderId++;
  17397. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  17398. if (!this.activeCamera)
  17399. throw new Error("Active camera not set");
  17400. // Viewport
  17401. engine.setViewport(this.activeCamera.viewport);
  17402. // Camera
  17403. this.updateTransformMatrix();
  17404. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  17405. }
  17406. }
  17407. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  17408. this._renderId++;
  17409. }
  17410. if (this.customRenderTargets.length > 0) {
  17411. engine.restoreDefaultFramebuffer();
  17412. }
  17413. this._renderTargetsDuration.endMonitoring();
  17414. this.activeCamera = currentActiveCamera;
  17415. // Procedural textures
  17416. if (this.proceduralTexturesEnabled) {
  17417. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17418. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  17419. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  17420. if (proceduralTexture._shouldRender()) {
  17421. proceduralTexture.render();
  17422. }
  17423. }
  17424. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  17425. }
  17426. // Clear
  17427. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  17428. // Shadows
  17429. if (this.shadowsEnabled) {
  17430. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  17431. var light = this.lights[lightIndex];
  17432. var shadowGenerator = light.getShadowGenerator();
  17433. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  17434. this._renderTargets.push(shadowGenerator.getShadowMap());
  17435. }
  17436. }
  17437. }
  17438. // Depth renderer
  17439. if (this._depthRenderer) {
  17440. this._renderTargets.push(this._depthRenderer.getDepthMap());
  17441. }
  17442. // RenderPipeline
  17443. this.postProcessRenderPipelineManager.update();
  17444. // Multi-cameras?
  17445. if (this.activeCameras.length > 0) {
  17446. var currentRenderId = this._renderId;
  17447. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  17448. this._renderId = currentRenderId;
  17449. if (cameraIndex > 0) {
  17450. this._engine.clear(0, false, true, true);
  17451. }
  17452. this._processSubCameras(this.activeCameras[cameraIndex]);
  17453. }
  17454. }
  17455. else {
  17456. if (!this.activeCamera) {
  17457. throw new Error("No camera defined");
  17458. }
  17459. this._processSubCameras(this.activeCamera);
  17460. }
  17461. // Intersection checks
  17462. this._checkIntersections();
  17463. // Update the audio listener attached to the camera
  17464. if (BABYLON.AudioEngine) {
  17465. this._updateAudioParameters();
  17466. }
  17467. // After render
  17468. if (this.afterRender) {
  17469. this.afterRender();
  17470. }
  17471. this.onAfterRenderObservable.notifyObservers(this);
  17472. // Cleaning
  17473. for (var index = 0; index < this._toBeDisposed.length; index++) {
  17474. this._toBeDisposed.data[index].dispose();
  17475. this._toBeDisposed[index] = null;
  17476. }
  17477. this._toBeDisposed.reset();
  17478. if (this.dumpNextRenderTargets) {
  17479. this.dumpNextRenderTargets = false;
  17480. }
  17481. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  17482. this._lastFrameDuration.endMonitoring();
  17483. this._totalMeshesCounter.addCount(this.meshes.length, true);
  17484. this._totalLightsCounter.addCount(this.lights.length, true);
  17485. this._totalMaterialsCounter.addCount(this.materials.length, true);
  17486. this._totalTexturesCounter.addCount(this.textures.length, true);
  17487. this._activeBones.addCount(0, true);
  17488. this._activeIndices.addCount(0, true);
  17489. this._activeParticles.addCount(0, true);
  17490. };
  17491. Scene.prototype._updateAudioParameters = function () {
  17492. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  17493. return;
  17494. }
  17495. var listeningCamera;
  17496. var audioEngine = BABYLON.Engine.audioEngine;
  17497. if (this.activeCameras.length > 0) {
  17498. listeningCamera = this.activeCameras[0];
  17499. }
  17500. else {
  17501. listeningCamera = this.activeCamera;
  17502. }
  17503. if (listeningCamera && audioEngine.canUseWebAudio) {
  17504. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  17505. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  17506. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  17507. cameraDirection.normalize();
  17508. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  17509. var i;
  17510. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17511. var sound = this.mainSoundTrack.soundCollection[i];
  17512. if (sound.useCustomAttenuation) {
  17513. sound.updateDistanceFromListener();
  17514. }
  17515. }
  17516. for (i = 0; i < this.soundTracks.length; i++) {
  17517. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17518. sound = this.soundTracks[i].soundCollection[j];
  17519. if (sound.useCustomAttenuation) {
  17520. sound.updateDistanceFromListener();
  17521. }
  17522. }
  17523. }
  17524. }
  17525. };
  17526. Object.defineProperty(Scene.prototype, "audioEnabled", {
  17527. // Audio
  17528. get: function () {
  17529. return this._audioEnabled;
  17530. },
  17531. set: function (value) {
  17532. this._audioEnabled = value;
  17533. if (BABYLON.AudioEngine) {
  17534. if (this._audioEnabled) {
  17535. this._enableAudio();
  17536. }
  17537. else {
  17538. this._disableAudio();
  17539. }
  17540. }
  17541. },
  17542. enumerable: true,
  17543. configurable: true
  17544. });
  17545. Scene.prototype._disableAudio = function () {
  17546. var i;
  17547. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17548. this.mainSoundTrack.soundCollection[i].pause();
  17549. }
  17550. for (i = 0; i < this.soundTracks.length; i++) {
  17551. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17552. this.soundTracks[i].soundCollection[j].pause();
  17553. }
  17554. }
  17555. };
  17556. Scene.prototype._enableAudio = function () {
  17557. var i;
  17558. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  17559. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  17560. this.mainSoundTrack.soundCollection[i].play();
  17561. }
  17562. }
  17563. for (i = 0; i < this.soundTracks.length; i++) {
  17564. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  17565. if (this.soundTracks[i].soundCollection[j].isPaused) {
  17566. this.soundTracks[i].soundCollection[j].play();
  17567. }
  17568. }
  17569. }
  17570. };
  17571. Object.defineProperty(Scene.prototype, "headphone", {
  17572. get: function () {
  17573. return this._headphone;
  17574. },
  17575. set: function (value) {
  17576. this._headphone = value;
  17577. if (BABYLON.AudioEngine) {
  17578. if (this._headphone) {
  17579. this._switchAudioModeForHeadphones();
  17580. }
  17581. else {
  17582. this._switchAudioModeForNormalSpeakers();
  17583. }
  17584. }
  17585. },
  17586. enumerable: true,
  17587. configurable: true
  17588. });
  17589. Scene.prototype._switchAudioModeForHeadphones = function () {
  17590. this.mainSoundTrack.switchPanningModelToHRTF();
  17591. for (var i = 0; i < this.soundTracks.length; i++) {
  17592. this.soundTracks[i].switchPanningModelToHRTF();
  17593. }
  17594. };
  17595. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  17596. this.mainSoundTrack.switchPanningModelToEqualPower();
  17597. for (var i = 0; i < this.soundTracks.length; i++) {
  17598. this.soundTracks[i].switchPanningModelToEqualPower();
  17599. }
  17600. };
  17601. Scene.prototype.enableDepthRenderer = function () {
  17602. if (this._depthRenderer) {
  17603. return this._depthRenderer;
  17604. }
  17605. this._depthRenderer = new BABYLON.DepthRenderer(this);
  17606. return this._depthRenderer;
  17607. };
  17608. Scene.prototype.disableDepthRenderer = function () {
  17609. if (!this._depthRenderer) {
  17610. return;
  17611. }
  17612. this._depthRenderer.dispose();
  17613. this._depthRenderer = null;
  17614. };
  17615. Scene.prototype.freezeMaterials = function () {
  17616. for (var i = 0; i < this.materials.length; i++) {
  17617. this.materials[i].freeze();
  17618. }
  17619. };
  17620. Scene.prototype.unfreezeMaterials = function () {
  17621. for (var i = 0; i < this.materials.length; i++) {
  17622. this.materials[i].unfreeze();
  17623. }
  17624. };
  17625. Scene.prototype.dispose = function () {
  17626. this.beforeRender = null;
  17627. this.afterRender = null;
  17628. this.skeletons = [];
  17629. this._boundingBoxRenderer.dispose();
  17630. if (this._depthRenderer) {
  17631. this._depthRenderer.dispose();
  17632. }
  17633. // Debug layer
  17634. if (this._debugLayer) {
  17635. this._debugLayer.hide();
  17636. }
  17637. // Events
  17638. this.onDisposeObservable.notifyObservers(this);
  17639. this.onDisposeObservable.clear();
  17640. this.onBeforeRenderObservable.clear();
  17641. this.onAfterRenderObservable.clear();
  17642. this.detachControl();
  17643. // Release sounds & sounds tracks
  17644. if (BABYLON.AudioEngine) {
  17645. this.disposeSounds();
  17646. }
  17647. // Detach cameras
  17648. var canvas = this._engine.getRenderingCanvas();
  17649. var index;
  17650. for (index = 0; index < this.cameras.length; index++) {
  17651. this.cameras[index].detachControl(canvas);
  17652. }
  17653. // Release lights
  17654. while (this.lights.length) {
  17655. this.lights[0].dispose();
  17656. }
  17657. // Release meshes
  17658. while (this.meshes.length) {
  17659. this.meshes[0].dispose(true);
  17660. }
  17661. // Release cameras
  17662. while (this.cameras.length) {
  17663. this.cameras[0].dispose();
  17664. }
  17665. // Release materials
  17666. while (this.materials.length) {
  17667. this.materials[0].dispose();
  17668. }
  17669. // Release particles
  17670. while (this.particleSystems.length) {
  17671. this.particleSystems[0].dispose();
  17672. }
  17673. // Release sprites
  17674. while (this.spriteManagers.length) {
  17675. this.spriteManagers[0].dispose();
  17676. }
  17677. // Release layers
  17678. while (this.layers.length) {
  17679. this.layers[0].dispose();
  17680. }
  17681. // Release textures
  17682. while (this.textures.length) {
  17683. this.textures[0].dispose();
  17684. }
  17685. // Post-processes
  17686. this.postProcessManager.dispose();
  17687. // Physics
  17688. if (this._physicsEngine) {
  17689. this.disablePhysicsEngine();
  17690. }
  17691. // Remove from engine
  17692. index = this._engine.scenes.indexOf(this);
  17693. if (index > -1) {
  17694. this._engine.scenes.splice(index, 1);
  17695. }
  17696. this._engine.wipeCaches();
  17697. };
  17698. // Release sounds & sounds tracks
  17699. Scene.prototype.disposeSounds = function () {
  17700. this.mainSoundTrack.dispose();
  17701. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  17702. this.soundTracks[scIndex].dispose();
  17703. }
  17704. };
  17705. // Octrees
  17706. Scene.prototype.getWorldExtends = function () {
  17707. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17708. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17709. for (var index = 0; index < this.meshes.length; index++) {
  17710. var mesh = this.meshes[index];
  17711. mesh.computeWorldMatrix(true);
  17712. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  17713. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  17714. BABYLON.Tools.CheckExtends(minBox, min, max);
  17715. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17716. }
  17717. return {
  17718. min: min,
  17719. max: max
  17720. };
  17721. };
  17722. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  17723. if (maxCapacity === void 0) { maxCapacity = 64; }
  17724. if (maxDepth === void 0) { maxDepth = 2; }
  17725. if (!this._selectionOctree) {
  17726. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  17727. }
  17728. var worldExtends = this.getWorldExtends();
  17729. // Update octree
  17730. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  17731. return this._selectionOctree;
  17732. };
  17733. // Picking
  17734. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  17735. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  17736. var engine = this._engine;
  17737. if (!camera) {
  17738. if (!this.activeCamera)
  17739. throw new Error("Active camera not set");
  17740. camera = this.activeCamera;
  17741. }
  17742. var cameraViewport = camera.viewport;
  17743. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17744. // Moving coordinates to local viewport world
  17745. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17746. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17747. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  17748. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  17749. };
  17750. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  17751. var engine = this._engine;
  17752. if (!camera) {
  17753. if (!this.activeCamera)
  17754. throw new Error("Active camera not set");
  17755. camera = this.activeCamera;
  17756. }
  17757. var cameraViewport = camera.viewport;
  17758. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  17759. var identity = BABYLON.Matrix.Identity();
  17760. // Moving coordinates to local viewport world
  17761. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  17762. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  17763. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  17764. };
  17765. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  17766. var pickingInfo = null;
  17767. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  17768. var mesh = this.meshes[meshIndex];
  17769. if (predicate) {
  17770. if (!predicate(mesh)) {
  17771. continue;
  17772. }
  17773. }
  17774. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  17775. continue;
  17776. }
  17777. var world = mesh.getWorldMatrix();
  17778. var ray = rayFunction(world);
  17779. var result = mesh.intersects(ray, fastCheck);
  17780. if (!result || !result.hit)
  17781. continue;
  17782. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17783. continue;
  17784. pickingInfo = result;
  17785. if (fastCheck) {
  17786. break;
  17787. }
  17788. }
  17789. return pickingInfo || new BABYLON.PickingInfo();
  17790. };
  17791. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  17792. var pickingInfo = null;
  17793. camera = camera || this.activeCamera;
  17794. if (this.spriteManagers.length > 0) {
  17795. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  17796. var spriteManager = this.spriteManagers[spriteIndex];
  17797. if (!spriteManager.isPickable) {
  17798. continue;
  17799. }
  17800. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  17801. if (!result || !result.hit)
  17802. continue;
  17803. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  17804. continue;
  17805. pickingInfo = result;
  17806. if (fastCheck) {
  17807. break;
  17808. }
  17809. }
  17810. }
  17811. return pickingInfo || new BABYLON.PickingInfo();
  17812. };
  17813. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  17814. var _this = this;
  17815. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17816. /// <param name="x">X position on screen</param>
  17817. /// <param name="y">Y position on screen</param>
  17818. /// <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>
  17819. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17820. /// <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>
  17821. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  17822. };
  17823. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  17824. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  17825. /// <param name="x">X position on screen</param>
  17826. /// <param name="y">Y position on screen</param>
  17827. /// <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>
  17828. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  17829. /// <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>
  17830. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  17831. };
  17832. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  17833. var _this = this;
  17834. return this._internalPick(function (world) {
  17835. if (!_this._pickWithRayInverseMatrix) {
  17836. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  17837. }
  17838. world.invertToRef(_this._pickWithRayInverseMatrix);
  17839. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  17840. }, predicate, fastCheck);
  17841. };
  17842. Scene.prototype.setPointerOverMesh = function (mesh) {
  17843. if (this._pointerOverMesh === mesh) {
  17844. return;
  17845. }
  17846. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17847. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17848. }
  17849. this._pointerOverMesh = mesh;
  17850. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  17851. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  17852. }
  17853. };
  17854. Scene.prototype.getPointerOverMesh = function () {
  17855. return this._pointerOverMesh;
  17856. };
  17857. Scene.prototype.setPointerOverSprite = function (sprite) {
  17858. if (this._pointerOverSprite === sprite) {
  17859. return;
  17860. }
  17861. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17862. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17863. }
  17864. this._pointerOverSprite = sprite;
  17865. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  17866. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  17867. }
  17868. };
  17869. Scene.prototype.getPointerOverSprite = function () {
  17870. return this._pointerOverSprite;
  17871. };
  17872. // Physics
  17873. Scene.prototype.getPhysicsEngine = function () {
  17874. return this._physicsEngine;
  17875. };
  17876. /**
  17877. * Enables physics to the current scene
  17878. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  17879. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  17880. * @return {boolean} was the physics engine initialized
  17881. */
  17882. Scene.prototype.enablePhysics = function (gravity, plugin) {
  17883. if (this._physicsEngine) {
  17884. return true;
  17885. }
  17886. try {
  17887. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  17888. return true;
  17889. }
  17890. catch (e) {
  17891. BABYLON.Tools.Error(e.message);
  17892. return false;
  17893. }
  17894. };
  17895. Scene.prototype.disablePhysicsEngine = function () {
  17896. if (!this._physicsEngine) {
  17897. return;
  17898. }
  17899. this._physicsEngine.dispose();
  17900. this._physicsEngine = undefined;
  17901. };
  17902. Scene.prototype.isPhysicsEnabled = function () {
  17903. return this._physicsEngine !== undefined;
  17904. };
  17905. /**
  17906. *
  17907. * Sets the gravity of the physics engine (and NOT of the scene)
  17908. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  17909. */
  17910. Scene.prototype.setGravity = function (gravity) {
  17911. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  17912. if (!this._physicsEngine) {
  17913. return;
  17914. }
  17915. this._physicsEngine.setGravity(gravity);
  17916. };
  17917. /**
  17918. * Legacy support, using the new API
  17919. * @Deprecated
  17920. */
  17921. Scene.prototype.createCompoundImpostor = function (parts, options) {
  17922. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  17923. if (parts.parts) {
  17924. options = parts;
  17925. parts = parts.parts;
  17926. }
  17927. var mainMesh = parts[0].mesh;
  17928. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  17929. for (var index = 1; index < parts.length; index++) {
  17930. var mesh = parts[index].mesh;
  17931. if (mesh.parent !== mainMesh) {
  17932. mesh.position = mesh.position.subtract(mainMesh.position);
  17933. mesh.parent = mainMesh;
  17934. }
  17935. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  17936. }
  17937. mainMesh.physicsImpostor.forceUpdate();
  17938. };
  17939. Scene.prototype.deleteCompoundImpostor = function (compound) {
  17940. var mesh = compound.parts[0].mesh;
  17941. mesh.physicsImpostor.dispose();
  17942. mesh.physicsImpostor = null;
  17943. };
  17944. // Misc.
  17945. Scene.prototype.createDefaultCameraOrLight = function () {
  17946. // Light
  17947. if (this.lights.length === 0) {
  17948. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  17949. }
  17950. // Camera
  17951. if (!this.activeCamera) {
  17952. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  17953. // Compute position
  17954. var worldExtends = this.getWorldExtends();
  17955. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  17956. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  17957. camera.setTarget(worldCenter);
  17958. this.activeCamera = camera;
  17959. }
  17960. };
  17961. // Tags
  17962. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  17963. if (tagsQuery === undefined) {
  17964. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  17965. return list;
  17966. }
  17967. var listByTags = [];
  17968. forEach = forEach || (function (item) { return; });
  17969. for (var i in list) {
  17970. var item = list[i];
  17971. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  17972. listByTags.push(item);
  17973. forEach(item);
  17974. }
  17975. }
  17976. return listByTags;
  17977. };
  17978. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  17979. return this._getByTags(this.meshes, tagsQuery, forEach);
  17980. };
  17981. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  17982. return this._getByTags(this.cameras, tagsQuery, forEach);
  17983. };
  17984. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  17985. return this._getByTags(this.lights, tagsQuery, forEach);
  17986. };
  17987. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  17988. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  17989. };
  17990. /**
  17991. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  17992. * This allowed control for front to back rendering or reversly depending of the special needs.
  17993. *
  17994. * @param renderingGroupId The rendering group id corresponding to its index
  17995. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  17996. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  17997. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  17998. */
  17999. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18000. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18001. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18002. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18003. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18004. };
  18005. /**
  18006. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18007. *
  18008. * @param renderingGroupId The rendering group id corresponding to its index
  18009. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18010. */
  18011. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18012. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18013. };
  18014. // Statics
  18015. Scene._FOGMODE_NONE = 0;
  18016. Scene._FOGMODE_EXP = 1;
  18017. Scene._FOGMODE_EXP2 = 2;
  18018. Scene._FOGMODE_LINEAR = 3;
  18019. Scene.MinDeltaTime = 1.0;
  18020. Scene.MaxDeltaTime = 1000.0;
  18021. return Scene;
  18022. }());
  18023. BABYLON.Scene = Scene;
  18024. })(BABYLON || (BABYLON = {}));
  18025. var BABYLON;
  18026. (function (BABYLON) {
  18027. var Buffer = (function () {
  18028. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18029. if (engine instanceof BABYLON.Mesh) {
  18030. this._engine = engine.getScene().getEngine();
  18031. }
  18032. else {
  18033. this._engine = engine;
  18034. }
  18035. this._updatable = updatable;
  18036. this._data = data;
  18037. this._strideSize = stride;
  18038. if (!postponeInternalCreation) {
  18039. this.create();
  18040. }
  18041. this._instanced = instanced;
  18042. }
  18043. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18044. // a lot of these parameters are ignored as they are overriden by the buffer
  18045. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18046. };
  18047. // Properties
  18048. Buffer.prototype.isUpdatable = function () {
  18049. return this._updatable;
  18050. };
  18051. Buffer.prototype.getData = function () {
  18052. return this._data;
  18053. };
  18054. Buffer.prototype.getBuffer = function () {
  18055. return this._buffer;
  18056. };
  18057. Buffer.prototype.getStrideSize = function () {
  18058. return this._strideSize;
  18059. };
  18060. Buffer.prototype.getIsInstanced = function () {
  18061. return this._instanced;
  18062. };
  18063. // Methods
  18064. Buffer.prototype.create = function (data) {
  18065. if (!data && this._buffer) {
  18066. return; // nothing to do
  18067. }
  18068. data = data || this._data;
  18069. if (!this._buffer) {
  18070. if (this._updatable) {
  18071. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18072. this._data = data;
  18073. }
  18074. else {
  18075. this._buffer = this._engine.createVertexBuffer(data);
  18076. }
  18077. }
  18078. else if (this._updatable) {
  18079. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18080. this._data = data;
  18081. }
  18082. };
  18083. Buffer.prototype.update = function (data) {
  18084. this.create(data);
  18085. };
  18086. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18087. if (!this._buffer) {
  18088. return;
  18089. }
  18090. if (this._updatable) {
  18091. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18092. this._data = null;
  18093. }
  18094. };
  18095. Buffer.prototype.dispose = function () {
  18096. if (!this._buffer) {
  18097. return;
  18098. }
  18099. if (this._engine._releaseBuffer(this._buffer)) {
  18100. this._buffer = null;
  18101. }
  18102. };
  18103. return Buffer;
  18104. }());
  18105. BABYLON.Buffer = Buffer;
  18106. })(BABYLON || (BABYLON = {}));
  18107. var BABYLON;
  18108. (function (BABYLON) {
  18109. var VertexBuffer = (function () {
  18110. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18111. if (!stride) {
  18112. // Deduce stride from kind
  18113. switch (kind) {
  18114. case VertexBuffer.PositionKind:
  18115. stride = 3;
  18116. break;
  18117. case VertexBuffer.NormalKind:
  18118. stride = 3;
  18119. break;
  18120. case VertexBuffer.UVKind:
  18121. case VertexBuffer.UV2Kind:
  18122. case VertexBuffer.UV3Kind:
  18123. case VertexBuffer.UV4Kind:
  18124. case VertexBuffer.UV5Kind:
  18125. case VertexBuffer.UV6Kind:
  18126. stride = 2;
  18127. break;
  18128. case VertexBuffer.ColorKind:
  18129. stride = 4;
  18130. break;
  18131. case VertexBuffer.MatricesIndicesKind:
  18132. case VertexBuffer.MatricesIndicesExtraKind:
  18133. stride = 4;
  18134. break;
  18135. case VertexBuffer.MatricesWeightsKind:
  18136. case VertexBuffer.MatricesWeightsExtraKind:
  18137. stride = 4;
  18138. break;
  18139. }
  18140. }
  18141. if (data instanceof BABYLON.Buffer) {
  18142. if (!stride) {
  18143. stride = data.getStrideSize();
  18144. }
  18145. this._buffer = data;
  18146. this._ownsBuffer = false;
  18147. }
  18148. else {
  18149. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18150. this._ownsBuffer = true;
  18151. }
  18152. this._stride = stride;
  18153. this._offset = offset ? offset : 0;
  18154. this._size = size ? size : stride;
  18155. this._kind = kind;
  18156. }
  18157. VertexBuffer.prototype.getKind = function () {
  18158. return this._kind;
  18159. };
  18160. // Properties
  18161. VertexBuffer.prototype.isUpdatable = function () {
  18162. return this._buffer.isUpdatable();
  18163. };
  18164. VertexBuffer.prototype.getData = function () {
  18165. return this._buffer.getData();
  18166. };
  18167. VertexBuffer.prototype.getBuffer = function () {
  18168. return this._buffer.getBuffer();
  18169. };
  18170. VertexBuffer.prototype.getStrideSize = function () {
  18171. return this._stride;
  18172. };
  18173. VertexBuffer.prototype.getOffset = function () {
  18174. return this._offset;
  18175. };
  18176. VertexBuffer.prototype.getSize = function () {
  18177. return this._size;
  18178. };
  18179. VertexBuffer.prototype.getIsInstanced = function () {
  18180. return this._buffer.getIsInstanced();
  18181. };
  18182. // Methods
  18183. VertexBuffer.prototype.create = function (data) {
  18184. return this._buffer.create(data);
  18185. };
  18186. VertexBuffer.prototype.update = function (data) {
  18187. return this._buffer.update(data);
  18188. };
  18189. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18190. return this._buffer.updateDirectly(data, offset);
  18191. };
  18192. VertexBuffer.prototype.dispose = function () {
  18193. if (this._ownsBuffer) {
  18194. this._buffer.dispose();
  18195. }
  18196. };
  18197. Object.defineProperty(VertexBuffer, "PositionKind", {
  18198. get: function () {
  18199. return VertexBuffer._PositionKind;
  18200. },
  18201. enumerable: true,
  18202. configurable: true
  18203. });
  18204. Object.defineProperty(VertexBuffer, "NormalKind", {
  18205. get: function () {
  18206. return VertexBuffer._NormalKind;
  18207. },
  18208. enumerable: true,
  18209. configurable: true
  18210. });
  18211. Object.defineProperty(VertexBuffer, "UVKind", {
  18212. get: function () {
  18213. return VertexBuffer._UVKind;
  18214. },
  18215. enumerable: true,
  18216. configurable: true
  18217. });
  18218. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18219. get: function () {
  18220. return VertexBuffer._UV2Kind;
  18221. },
  18222. enumerable: true,
  18223. configurable: true
  18224. });
  18225. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18226. get: function () {
  18227. return VertexBuffer._UV3Kind;
  18228. },
  18229. enumerable: true,
  18230. configurable: true
  18231. });
  18232. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18233. get: function () {
  18234. return VertexBuffer._UV4Kind;
  18235. },
  18236. enumerable: true,
  18237. configurable: true
  18238. });
  18239. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18240. get: function () {
  18241. return VertexBuffer._UV5Kind;
  18242. },
  18243. enumerable: true,
  18244. configurable: true
  18245. });
  18246. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18247. get: function () {
  18248. return VertexBuffer._UV6Kind;
  18249. },
  18250. enumerable: true,
  18251. configurable: true
  18252. });
  18253. Object.defineProperty(VertexBuffer, "ColorKind", {
  18254. get: function () {
  18255. return VertexBuffer._ColorKind;
  18256. },
  18257. enumerable: true,
  18258. configurable: true
  18259. });
  18260. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18261. get: function () {
  18262. return VertexBuffer._MatricesIndicesKind;
  18263. },
  18264. enumerable: true,
  18265. configurable: true
  18266. });
  18267. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18268. get: function () {
  18269. return VertexBuffer._MatricesWeightsKind;
  18270. },
  18271. enumerable: true,
  18272. configurable: true
  18273. });
  18274. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18275. get: function () {
  18276. return VertexBuffer._MatricesIndicesExtraKind;
  18277. },
  18278. enumerable: true,
  18279. configurable: true
  18280. });
  18281. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18282. get: function () {
  18283. return VertexBuffer._MatricesWeightsExtraKind;
  18284. },
  18285. enumerable: true,
  18286. configurable: true
  18287. });
  18288. // Enums
  18289. VertexBuffer._PositionKind = "position";
  18290. VertexBuffer._NormalKind = "normal";
  18291. VertexBuffer._UVKind = "uv";
  18292. VertexBuffer._UV2Kind = "uv2";
  18293. VertexBuffer._UV3Kind = "uv3";
  18294. VertexBuffer._UV4Kind = "uv4";
  18295. VertexBuffer._UV5Kind = "uv5";
  18296. VertexBuffer._UV6Kind = "uv6";
  18297. VertexBuffer._ColorKind = "color";
  18298. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18299. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18300. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18301. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18302. return VertexBuffer;
  18303. }());
  18304. BABYLON.VertexBuffer = VertexBuffer;
  18305. })(BABYLON || (BABYLON = {}));
  18306. var BABYLON;
  18307. (function (BABYLON) {
  18308. /**
  18309. * Creates an instance based on a source mesh.
  18310. */
  18311. var InstancedMesh = (function (_super) {
  18312. __extends(InstancedMesh, _super);
  18313. function InstancedMesh(name, source) {
  18314. _super.call(this, name, source.getScene());
  18315. source.instances.push(this);
  18316. this._sourceMesh = source;
  18317. this.position.copyFrom(source.position);
  18318. this.rotation.copyFrom(source.rotation);
  18319. this.scaling.copyFrom(source.scaling);
  18320. if (source.rotationQuaternion) {
  18321. this.rotationQuaternion = source.rotationQuaternion.clone();
  18322. }
  18323. this.infiniteDistance = source.infiniteDistance;
  18324. this.setPivotMatrix(source.getPivotMatrix());
  18325. this.refreshBoundingInfo();
  18326. this._syncSubMeshes();
  18327. }
  18328. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  18329. // Methods
  18330. get: function () {
  18331. return this._sourceMesh.receiveShadows;
  18332. },
  18333. enumerable: true,
  18334. configurable: true
  18335. });
  18336. Object.defineProperty(InstancedMesh.prototype, "material", {
  18337. get: function () {
  18338. return this._sourceMesh.material;
  18339. },
  18340. enumerable: true,
  18341. configurable: true
  18342. });
  18343. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  18344. get: function () {
  18345. return this._sourceMesh.visibility;
  18346. },
  18347. enumerable: true,
  18348. configurable: true
  18349. });
  18350. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  18351. get: function () {
  18352. return this._sourceMesh.skeleton;
  18353. },
  18354. enumerable: true,
  18355. configurable: true
  18356. });
  18357. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  18358. get: function () {
  18359. return this._sourceMesh.renderingGroupId;
  18360. },
  18361. enumerable: true,
  18362. configurable: true
  18363. });
  18364. InstancedMesh.prototype.getTotalVertices = function () {
  18365. return this._sourceMesh.getTotalVertices();
  18366. };
  18367. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  18368. get: function () {
  18369. return this._sourceMesh;
  18370. },
  18371. enumerable: true,
  18372. configurable: true
  18373. });
  18374. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18375. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  18376. };
  18377. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  18378. return this._sourceMesh.isVerticesDataPresent(kind);
  18379. };
  18380. InstancedMesh.prototype.getIndices = function () {
  18381. return this._sourceMesh.getIndices();
  18382. };
  18383. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  18384. get: function () {
  18385. return this._sourceMesh._positions;
  18386. },
  18387. enumerable: true,
  18388. configurable: true
  18389. });
  18390. InstancedMesh.prototype.refreshBoundingInfo = function () {
  18391. var meshBB = this._sourceMesh.getBoundingInfo();
  18392. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  18393. this._updateBoundingInfo();
  18394. };
  18395. InstancedMesh.prototype._preActivate = function () {
  18396. if (this._currentLOD) {
  18397. this._currentLOD._preActivate();
  18398. }
  18399. };
  18400. InstancedMesh.prototype._activate = function (renderId) {
  18401. if (this._currentLOD) {
  18402. this._currentLOD._registerInstanceForRenderId(this, renderId);
  18403. }
  18404. };
  18405. InstancedMesh.prototype.getLOD = function (camera) {
  18406. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  18407. if (this._currentLOD === this.sourceMesh) {
  18408. return this;
  18409. }
  18410. return this._currentLOD;
  18411. };
  18412. InstancedMesh.prototype._syncSubMeshes = function () {
  18413. this.releaseSubMeshes();
  18414. if (this._sourceMesh.subMeshes) {
  18415. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  18416. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  18417. }
  18418. }
  18419. };
  18420. InstancedMesh.prototype._generatePointsArray = function () {
  18421. return this._sourceMesh._generatePointsArray();
  18422. };
  18423. // Clone
  18424. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18425. var result = this._sourceMesh.createInstance(name);
  18426. // Deep copy
  18427. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  18428. // Bounding info
  18429. this.refreshBoundingInfo();
  18430. // Parent
  18431. if (newParent) {
  18432. result.parent = newParent;
  18433. }
  18434. if (!doNotCloneChildren) {
  18435. // Children
  18436. for (var index = 0; index < this.getScene().meshes.length; index++) {
  18437. var mesh = this.getScene().meshes[index];
  18438. if (mesh.parent === this) {
  18439. mesh.clone(mesh.name, result);
  18440. }
  18441. }
  18442. }
  18443. result.computeWorldMatrix(true);
  18444. return result;
  18445. };
  18446. // Dispoe
  18447. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  18448. // Remove from mesh
  18449. var index = this._sourceMesh.instances.indexOf(this);
  18450. this._sourceMesh.instances.splice(index, 1);
  18451. _super.prototype.dispose.call(this, doNotRecurse);
  18452. };
  18453. return InstancedMesh;
  18454. }(BABYLON.AbstractMesh));
  18455. BABYLON.InstancedMesh = InstancedMesh;
  18456. })(BABYLON || (BABYLON = {}));
  18457. var BABYLON;
  18458. (function (BABYLON) {
  18459. var _InstancesBatch = (function () {
  18460. function _InstancesBatch() {
  18461. this.mustReturn = false;
  18462. this.visibleInstances = new Array();
  18463. this.renderSelf = new Array();
  18464. }
  18465. return _InstancesBatch;
  18466. }());
  18467. BABYLON._InstancesBatch = _InstancesBatch;
  18468. var Mesh = (function (_super) {
  18469. __extends(Mesh, _super);
  18470. /**
  18471. * @constructor
  18472. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  18473. * @param {Scene} scene The scene to add this mesh to.
  18474. * @param {Node} parent The parent of this mesh, if it has one
  18475. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  18476. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  18477. * When false, achieved by calling a clone(), also passing False.
  18478. * This will make creation of children, recursive.
  18479. */
  18480. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  18481. if (parent === void 0) { parent = null; }
  18482. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  18483. _super.call(this, name, scene);
  18484. // Events
  18485. /**
  18486. * An event triggered before rendering the mesh
  18487. * @type {BABYLON.Observable}
  18488. */
  18489. this.onBeforeRenderObservable = new BABYLON.Observable();
  18490. /**
  18491. * An event triggered after rendering the mesh
  18492. * @type {BABYLON.Observable}
  18493. */
  18494. this.onAfterRenderObservable = new BABYLON.Observable();
  18495. /**
  18496. * An event triggered before drawing the mesh
  18497. * @type {BABYLON.Observable}
  18498. */
  18499. this.onBeforeDrawObservable = new BABYLON.Observable();
  18500. // Members
  18501. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  18502. this.instances = new Array();
  18503. this._LODLevels = new Array();
  18504. this._visibleInstances = {};
  18505. this._renderIdForInstances = new Array();
  18506. this._batchCache = new _InstancesBatch();
  18507. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  18508. this._sideOrientation = Mesh._DEFAULTSIDE;
  18509. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  18510. if (source) {
  18511. // Geometry
  18512. if (source._geometry) {
  18513. source._geometry.applyToMesh(this);
  18514. }
  18515. // Deep copy
  18516. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  18517. // Pivot
  18518. this.setPivotMatrix(source.getPivotMatrix());
  18519. this.id = name + "." + source.id;
  18520. // Material
  18521. this.material = source.material;
  18522. var index;
  18523. if (!doNotCloneChildren) {
  18524. // Children
  18525. for (index = 0; index < scene.meshes.length; index++) {
  18526. var mesh = scene.meshes[index];
  18527. if (mesh.parent === source) {
  18528. // doNotCloneChildren is always going to be False
  18529. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  18530. }
  18531. }
  18532. }
  18533. // Physics clone
  18534. var physicsEngine = this.getScene().getPhysicsEngine();
  18535. if (clonePhysicsImpostor && physicsEngine) {
  18536. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  18537. if (impostor) {
  18538. this.physicsImpostor = impostor.clone(this);
  18539. }
  18540. }
  18541. // Particles
  18542. for (index = 0; index < scene.particleSystems.length; index++) {
  18543. var system = scene.particleSystems[index];
  18544. if (system.emitter === source) {
  18545. system.clone(system.name, this);
  18546. }
  18547. }
  18548. this.computeWorldMatrix(true);
  18549. }
  18550. // Parent
  18551. if (parent !== null) {
  18552. this.parent = parent;
  18553. }
  18554. }
  18555. Object.defineProperty(Mesh, "FRONTSIDE", {
  18556. /**
  18557. * Mesh side orientation : usually the external or front surface
  18558. */
  18559. get: function () {
  18560. return Mesh._FRONTSIDE;
  18561. },
  18562. enumerable: true,
  18563. configurable: true
  18564. });
  18565. Object.defineProperty(Mesh, "BACKSIDE", {
  18566. /**
  18567. * Mesh side orientation : usually the internal or back surface
  18568. */
  18569. get: function () {
  18570. return Mesh._BACKSIDE;
  18571. },
  18572. enumerable: true,
  18573. configurable: true
  18574. });
  18575. Object.defineProperty(Mesh, "DOUBLESIDE", {
  18576. /**
  18577. * Mesh side orientation : both internal and external or front and back surfaces
  18578. */
  18579. get: function () {
  18580. return Mesh._DOUBLESIDE;
  18581. },
  18582. enumerable: true,
  18583. configurable: true
  18584. });
  18585. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  18586. /**
  18587. * Mesh side orientation : by default, `FRONTSIDE`
  18588. */
  18589. get: function () {
  18590. return Mesh._DEFAULTSIDE;
  18591. },
  18592. enumerable: true,
  18593. configurable: true
  18594. });
  18595. Object.defineProperty(Mesh, "NO_CAP", {
  18596. /**
  18597. * Mesh cap setting : no cap
  18598. */
  18599. get: function () {
  18600. return Mesh._NO_CAP;
  18601. },
  18602. enumerable: true,
  18603. configurable: true
  18604. });
  18605. Object.defineProperty(Mesh, "CAP_START", {
  18606. /**
  18607. * Mesh cap setting : one cap at the beginning of the mesh
  18608. */
  18609. get: function () {
  18610. return Mesh._CAP_START;
  18611. },
  18612. enumerable: true,
  18613. configurable: true
  18614. });
  18615. Object.defineProperty(Mesh, "CAP_END", {
  18616. /**
  18617. * Mesh cap setting : one cap at the end of the mesh
  18618. */
  18619. get: function () {
  18620. return Mesh._CAP_END;
  18621. },
  18622. enumerable: true,
  18623. configurable: true
  18624. });
  18625. Object.defineProperty(Mesh, "CAP_ALL", {
  18626. /**
  18627. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  18628. */
  18629. get: function () {
  18630. return Mesh._CAP_ALL;
  18631. },
  18632. enumerable: true,
  18633. configurable: true
  18634. });
  18635. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  18636. set: function (callback) {
  18637. if (this._onBeforeDrawObserver) {
  18638. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  18639. }
  18640. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  18641. },
  18642. enumerable: true,
  18643. configurable: true
  18644. });
  18645. // Methods
  18646. /**
  18647. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  18648. */
  18649. Mesh.prototype.toString = function (fullDetails) {
  18650. var ret = _super.prototype.toString.call(this, fullDetails);
  18651. ret += ", n vertices: " + this.getTotalVertices();
  18652. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  18653. if (this.animations) {
  18654. for (var i = 0; i < this.animations.length; i++) {
  18655. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18656. }
  18657. }
  18658. if (fullDetails) {
  18659. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  18660. }
  18661. return ret;
  18662. };
  18663. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  18664. get: function () {
  18665. return this._LODLevels.length > 0;
  18666. },
  18667. enumerable: true,
  18668. configurable: true
  18669. });
  18670. Mesh.prototype._sortLODLevels = function () {
  18671. this._LODLevels.sort(function (a, b) {
  18672. if (a.distance < b.distance) {
  18673. return 1;
  18674. }
  18675. if (a.distance > b.distance) {
  18676. return -1;
  18677. }
  18678. return 0;
  18679. });
  18680. };
  18681. /**
  18682. * Add a mesh as LOD level triggered at the given distance.
  18683. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18684. * @param {number} distance The distance from the center of the object to show this level
  18685. * @param {Mesh} mesh The mesh to be added as LOD level
  18686. * @return {Mesh} This mesh (for chaining)
  18687. */
  18688. Mesh.prototype.addLODLevel = function (distance, mesh) {
  18689. if (mesh && mesh._masterMesh) {
  18690. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  18691. return this;
  18692. }
  18693. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  18694. this._LODLevels.push(level);
  18695. if (mesh) {
  18696. mesh._masterMesh = this;
  18697. }
  18698. this._sortLODLevels();
  18699. return this;
  18700. };
  18701. /**
  18702. * Returns the LOD level mesh at the passed distance or null if not found.
  18703. * It is related to the method `addLODLevel(distance, mesh)`.
  18704. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18705. */
  18706. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  18707. for (var index = 0; index < this._LODLevels.length; index++) {
  18708. var level = this._LODLevels[index];
  18709. if (level.distance === distance) {
  18710. return level.mesh;
  18711. }
  18712. }
  18713. return null;
  18714. };
  18715. /**
  18716. * Remove a mesh from the LOD array
  18717. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18718. * @param {Mesh} mesh The mesh to be removed.
  18719. * @return {Mesh} This mesh (for chaining)
  18720. */
  18721. Mesh.prototype.removeLODLevel = function (mesh) {
  18722. for (var index = 0; index < this._LODLevels.length; index++) {
  18723. if (this._LODLevels[index].mesh === mesh) {
  18724. this._LODLevels.splice(index, 1);
  18725. if (mesh) {
  18726. mesh._masterMesh = null;
  18727. }
  18728. }
  18729. }
  18730. this._sortLODLevels();
  18731. return this;
  18732. };
  18733. /**
  18734. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  18735. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  18736. */
  18737. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  18738. if (!this._LODLevels || this._LODLevels.length === 0) {
  18739. return this;
  18740. }
  18741. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  18742. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  18743. if (this.onLODLevelSelection) {
  18744. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  18745. }
  18746. return this;
  18747. }
  18748. for (var index = 0; index < this._LODLevels.length; index++) {
  18749. var level = this._LODLevels[index];
  18750. if (level.distance < distanceToCamera) {
  18751. if (level.mesh) {
  18752. level.mesh._preActivate();
  18753. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18754. }
  18755. if (this.onLODLevelSelection) {
  18756. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  18757. }
  18758. return level.mesh;
  18759. }
  18760. }
  18761. if (this.onLODLevelSelection) {
  18762. this.onLODLevelSelection(distanceToCamera, this, this);
  18763. }
  18764. return this;
  18765. };
  18766. Object.defineProperty(Mesh.prototype, "geometry", {
  18767. /**
  18768. * Returns the mesh internal Geometry object.
  18769. */
  18770. get: function () {
  18771. return this._geometry;
  18772. },
  18773. enumerable: true,
  18774. configurable: true
  18775. });
  18776. /**
  18777. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  18778. */
  18779. Mesh.prototype.getTotalVertices = function () {
  18780. if (!this._geometry) {
  18781. return 0;
  18782. }
  18783. return this._geometry.getTotalVertices();
  18784. };
  18785. /**
  18786. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  18787. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  18788. * Returns null if the mesh has no geometry or no vertex buffer.
  18789. * Possible `kind` values :
  18790. * - BABYLON.VertexBuffer.PositionKind
  18791. * - BABYLON.VertexBuffer.UVKind
  18792. * - BABYLON.VertexBuffer.UV2Kind
  18793. * - BABYLON.VertexBuffer.UV3Kind
  18794. * - BABYLON.VertexBuffer.UV4Kind
  18795. * - BABYLON.VertexBuffer.UV5Kind
  18796. * - BABYLON.VertexBuffer.UV6Kind
  18797. * - BABYLON.VertexBuffer.ColorKind
  18798. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18799. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18800. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18801. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18802. */
  18803. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  18804. if (!this._geometry) {
  18805. return null;
  18806. }
  18807. return this._geometry.getVerticesData(kind, copyWhenShared);
  18808. };
  18809. /**
  18810. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  18811. * Returns `undefined` if the mesh has no geometry.
  18812. * Possible `kind` values :
  18813. * - BABYLON.VertexBuffer.PositionKind
  18814. * - BABYLON.VertexBuffer.UVKind
  18815. * - BABYLON.VertexBuffer.UV2Kind
  18816. * - BABYLON.VertexBuffer.UV3Kind
  18817. * - BABYLON.VertexBuffer.UV4Kind
  18818. * - BABYLON.VertexBuffer.UV5Kind
  18819. * - BABYLON.VertexBuffer.UV6Kind
  18820. * - BABYLON.VertexBuffer.ColorKind
  18821. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18822. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18823. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18824. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18825. */
  18826. Mesh.prototype.getVertexBuffer = function (kind) {
  18827. if (!this._geometry) {
  18828. return undefined;
  18829. }
  18830. return this._geometry.getVertexBuffer(kind);
  18831. };
  18832. /**
  18833. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  18834. * Possible `kind` values :
  18835. * - BABYLON.VertexBuffer.PositionKind
  18836. * - BABYLON.VertexBuffer.UVKind
  18837. * - BABYLON.VertexBuffer.UV2Kind
  18838. * - BABYLON.VertexBuffer.UV3Kind
  18839. * - BABYLON.VertexBuffer.UV4Kind
  18840. * - BABYLON.VertexBuffer.UV5Kind
  18841. * - BABYLON.VertexBuffer.UV6Kind
  18842. * - BABYLON.VertexBuffer.ColorKind
  18843. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18844. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18845. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18846. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18847. */
  18848. Mesh.prototype.isVerticesDataPresent = function (kind) {
  18849. if (!this._geometry) {
  18850. if (this._delayInfo) {
  18851. return this._delayInfo.indexOf(kind) !== -1;
  18852. }
  18853. return false;
  18854. }
  18855. return this._geometry.isVerticesDataPresent(kind);
  18856. };
  18857. /**
  18858. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  18859. * Possible `kind` values :
  18860. * - BABYLON.VertexBuffer.PositionKind
  18861. * - BABYLON.VertexBuffer.UVKind
  18862. * - BABYLON.VertexBuffer.UV2Kind
  18863. * - BABYLON.VertexBuffer.UV3Kind
  18864. * - BABYLON.VertexBuffer.UV4Kind
  18865. * - BABYLON.VertexBuffer.UV5Kind
  18866. * - BABYLON.VertexBuffer.UV6Kind
  18867. * - BABYLON.VertexBuffer.ColorKind
  18868. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18869. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18870. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18871. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18872. */
  18873. Mesh.prototype.getVerticesDataKinds = function () {
  18874. if (!this._geometry) {
  18875. var result = [];
  18876. if (this._delayInfo) {
  18877. for (var kind in this._delayInfo) {
  18878. result.push(kind);
  18879. }
  18880. }
  18881. return result;
  18882. }
  18883. return this._geometry.getVerticesDataKinds();
  18884. };
  18885. /**
  18886. * Returns a positive integer : the total number of indices in this mesh geometry.
  18887. * Returns zero if the mesh has no geometry.
  18888. */
  18889. Mesh.prototype.getTotalIndices = function () {
  18890. if (!this._geometry) {
  18891. return 0;
  18892. }
  18893. return this._geometry.getTotalIndices();
  18894. };
  18895. /**
  18896. * Returns an array of integers or a Int32Array populated with the mesh indices.
  18897. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  18898. * Returns an empty array if the mesh has no geometry.
  18899. */
  18900. Mesh.prototype.getIndices = function (copyWhenShared) {
  18901. if (!this._geometry) {
  18902. return [];
  18903. }
  18904. return this._geometry.getIndices(copyWhenShared);
  18905. };
  18906. Object.defineProperty(Mesh.prototype, "isBlocked", {
  18907. get: function () {
  18908. return this._masterMesh !== null && this._masterMesh !== undefined;
  18909. },
  18910. enumerable: true,
  18911. configurable: true
  18912. });
  18913. /**
  18914. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  18915. */
  18916. Mesh.prototype.isReady = function () {
  18917. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18918. return false;
  18919. }
  18920. return _super.prototype.isReady.call(this);
  18921. };
  18922. /**
  18923. * Boolean : true if the mesh has been disposed.
  18924. */
  18925. Mesh.prototype.isDisposed = function () {
  18926. return this._isDisposed;
  18927. };
  18928. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  18929. get: function () {
  18930. return this._sideOrientation;
  18931. },
  18932. /**
  18933. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  18934. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  18935. */
  18936. set: function (sideO) {
  18937. this._sideOrientation = sideO;
  18938. },
  18939. enumerable: true,
  18940. configurable: true
  18941. });
  18942. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  18943. /**
  18944. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  18945. * This property is pertinent only for updatable parametric shapes.
  18946. */
  18947. get: function () {
  18948. return this._areNormalsFrozen;
  18949. },
  18950. enumerable: true,
  18951. configurable: true
  18952. });
  18953. /**
  18954. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18955. * It has no effect at all on other shapes.
  18956. * It prevents the mesh normals from being recomputed on next `positions` array update.
  18957. */
  18958. Mesh.prototype.freezeNormals = function () {
  18959. this._areNormalsFrozen = true;
  18960. };
  18961. /**
  18962. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  18963. * It has no effect at all on other shapes.
  18964. * It reactivates the mesh normals computation if it was previously frozen.
  18965. */
  18966. Mesh.prototype.unfreezeNormals = function () {
  18967. this._areNormalsFrozen = false;
  18968. };
  18969. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  18970. /**
  18971. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  18972. */
  18973. set: function (count) {
  18974. this._overridenInstanceCount = count;
  18975. },
  18976. enumerable: true,
  18977. configurable: true
  18978. });
  18979. // Methods
  18980. Mesh.prototype._preActivate = function () {
  18981. var sceneRenderId = this.getScene().getRenderId();
  18982. if (this._preActivateId === sceneRenderId) {
  18983. return;
  18984. }
  18985. this._preActivateId = sceneRenderId;
  18986. this._visibleInstances = null;
  18987. };
  18988. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18989. if (this._visibleInstances) {
  18990. this._visibleInstances.intermediateDefaultRenderId = renderId;
  18991. }
  18992. };
  18993. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  18994. if (!this._visibleInstances) {
  18995. this._visibleInstances = {};
  18996. this._visibleInstances.defaultRenderId = renderId;
  18997. this._visibleInstances.selfDefaultRenderId = this._renderId;
  18998. }
  18999. if (!this._visibleInstances[renderId]) {
  19000. this._visibleInstances[renderId] = new Array();
  19001. }
  19002. this._visibleInstances[renderId].push(instance);
  19003. };
  19004. /**
  19005. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19006. * This means the mesh underlying bounding box and sphere are recomputed.
  19007. */
  19008. Mesh.prototype.refreshBoundingInfo = function () {
  19009. if (this._boundingInfo.isLocked) {
  19010. return;
  19011. }
  19012. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19013. if (data) {
  19014. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19015. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19016. }
  19017. if (this.subMeshes) {
  19018. for (var index = 0; index < this.subMeshes.length; index++) {
  19019. this.subMeshes[index].refreshBoundingInfo();
  19020. }
  19021. }
  19022. this._updateBoundingInfo();
  19023. };
  19024. Mesh.prototype._createGlobalSubMesh = function () {
  19025. var totalVertices = this.getTotalVertices();
  19026. if (!totalVertices || !this.getIndices()) {
  19027. return null;
  19028. }
  19029. this.releaseSubMeshes();
  19030. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19031. };
  19032. Mesh.prototype.subdivide = function (count) {
  19033. if (count < 1) {
  19034. return;
  19035. }
  19036. var totalIndices = this.getTotalIndices();
  19037. var subdivisionSize = (totalIndices / count) | 0;
  19038. var offset = 0;
  19039. // Ensure that subdivisionSize is a multiple of 3
  19040. while (subdivisionSize % 3 !== 0) {
  19041. subdivisionSize++;
  19042. }
  19043. this.releaseSubMeshes();
  19044. for (var index = 0; index < count; index++) {
  19045. if (offset >= totalIndices) {
  19046. break;
  19047. }
  19048. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19049. offset += subdivisionSize;
  19050. }
  19051. this.synchronizeInstances();
  19052. };
  19053. /**
  19054. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19055. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19056. * The `data` are either a numeric array either a Float32Array.
  19057. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19058. * 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).
  19059. * Note that a new underlying VertexBuffer object is created each call.
  19060. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19061. *
  19062. * Possible `kind` values :
  19063. * - BABYLON.VertexBuffer.PositionKind
  19064. * - BABYLON.VertexBuffer.UVKind
  19065. * - BABYLON.VertexBuffer.UV2Kind
  19066. * - BABYLON.VertexBuffer.UV3Kind
  19067. * - BABYLON.VertexBuffer.UV4Kind
  19068. * - BABYLON.VertexBuffer.UV5Kind
  19069. * - BABYLON.VertexBuffer.UV6Kind
  19070. * - BABYLON.VertexBuffer.ColorKind
  19071. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19072. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19073. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19074. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19075. */
  19076. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19077. if (!this._geometry) {
  19078. var vertexData = new BABYLON.VertexData();
  19079. vertexData.set(data, kind);
  19080. var scene = this.getScene();
  19081. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19082. }
  19083. else {
  19084. this._geometry.setVerticesData(kind, data, updatable, stride);
  19085. }
  19086. };
  19087. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19088. if (!this._geometry) {
  19089. var scene = this.getScene();
  19090. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19091. }
  19092. this._geometry.setVerticesBuffer(buffer);
  19093. };
  19094. /**
  19095. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19096. * If the mesh has no geometry, it is simply returned as it is.
  19097. * The `data` are either a numeric array either a Float32Array.
  19098. * No new underlying VertexBuffer object is created.
  19099. * 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.
  19100. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19101. *
  19102. * Possible `kind` values :
  19103. * - BABYLON.VertexBuffer.PositionKind
  19104. * - BABYLON.VertexBuffer.UVKind
  19105. * - BABYLON.VertexBuffer.UV2Kind
  19106. * - BABYLON.VertexBuffer.UV3Kind
  19107. * - BABYLON.VertexBuffer.UV4Kind
  19108. * - BABYLON.VertexBuffer.UV5Kind
  19109. * - BABYLON.VertexBuffer.UV6Kind
  19110. * - BABYLON.VertexBuffer.ColorKind
  19111. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19112. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19113. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19114. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19115. */
  19116. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19117. if (!this._geometry) {
  19118. return;
  19119. }
  19120. if (!makeItUnique) {
  19121. this._geometry.updateVerticesData(kind, data, updateExtends);
  19122. }
  19123. else {
  19124. this.makeGeometryUnique();
  19125. this.updateVerticesData(kind, data, updateExtends, false);
  19126. }
  19127. };
  19128. /**
  19129. * Deprecated since BabylonJS v2.3
  19130. */
  19131. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19132. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19133. if (!this._geometry) {
  19134. return;
  19135. }
  19136. if (!makeItUnique) {
  19137. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19138. }
  19139. else {
  19140. this.makeGeometryUnique();
  19141. this.updateVerticesDataDirectly(kind, data, offset, false);
  19142. }
  19143. };
  19144. /**
  19145. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19146. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19147. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19148. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19149. */
  19150. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19151. if (computeNormals === void 0) { computeNormals = true; }
  19152. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19153. positionFunction(positions);
  19154. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19155. if (computeNormals) {
  19156. var indices = this.getIndices();
  19157. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19158. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19159. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19160. }
  19161. };
  19162. Mesh.prototype.makeGeometryUnique = function () {
  19163. if (!this._geometry) {
  19164. return;
  19165. }
  19166. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19167. geometry.applyToMesh(this);
  19168. };
  19169. /**
  19170. * Sets the mesh indices.
  19171. * Expects an array populated with integers or a Int32Array.
  19172. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19173. * This method creates a new index buffer each call.
  19174. */
  19175. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19176. if (!this._geometry) {
  19177. var vertexData = new BABYLON.VertexData();
  19178. vertexData.indices = indices;
  19179. var scene = this.getScene();
  19180. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19181. }
  19182. else {
  19183. this._geometry.setIndices(indices, totalVertices);
  19184. }
  19185. };
  19186. /**
  19187. * Invert the geometry to move from a right handed system to a left handed one.
  19188. */
  19189. Mesh.prototype.toLeftHanded = function () {
  19190. if (!this._geometry) {
  19191. return;
  19192. }
  19193. this._geometry.toLeftHanded();
  19194. };
  19195. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19196. var engine = this.getScene().getEngine();
  19197. // Wireframe
  19198. var indexToBind;
  19199. if (this._unIndexed) {
  19200. indexToBind = null;
  19201. }
  19202. else {
  19203. switch (fillMode) {
  19204. case BABYLON.Material.PointFillMode:
  19205. indexToBind = null;
  19206. break;
  19207. case BABYLON.Material.WireFrameFillMode:
  19208. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19209. break;
  19210. default:
  19211. case BABYLON.Material.TriangleFillMode:
  19212. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19213. break;
  19214. }
  19215. }
  19216. // VBOs
  19217. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19218. };
  19219. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19220. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19221. return;
  19222. }
  19223. this.onBeforeDrawObservable.notifyObservers(this);
  19224. var engine = this.getScene().getEngine();
  19225. // Draw order
  19226. switch (fillMode) {
  19227. case BABYLON.Material.PointFillMode:
  19228. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19229. break;
  19230. case BABYLON.Material.WireFrameFillMode:
  19231. if (this._unIndexed) {
  19232. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19233. }
  19234. else {
  19235. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19236. }
  19237. break;
  19238. default:
  19239. if (this._unIndexed) {
  19240. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19241. }
  19242. else {
  19243. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19244. }
  19245. }
  19246. };
  19247. /**
  19248. * Registers for this mesh a javascript function called just before the rendering process.
  19249. * This function is passed the current mesh and doesn't return anything.
  19250. */
  19251. Mesh.prototype.registerBeforeRender = function (func) {
  19252. this.onBeforeRenderObservable.add(func);
  19253. };
  19254. /**
  19255. * Disposes a previously registered javascript function called before the rendering.
  19256. * This function is passed the current mesh and doesn't return anything.
  19257. */
  19258. Mesh.prototype.unregisterBeforeRender = function (func) {
  19259. this.onBeforeRenderObservable.removeCallback(func);
  19260. };
  19261. /**
  19262. * Registers for this mesh a javascript function called just after the rendering is complete.
  19263. * This function is passed the current mesh and doesn't return anything.
  19264. */
  19265. Mesh.prototype.registerAfterRender = function (func) {
  19266. this.onAfterRenderObservable.add(func);
  19267. };
  19268. /**
  19269. * Disposes a previously registered javascript function called after the rendering.
  19270. * This function is passed the current mesh and doesn't return anything.
  19271. */
  19272. Mesh.prototype.unregisterAfterRender = function (func) {
  19273. this.onAfterRenderObservable.removeCallback(func);
  19274. };
  19275. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19276. var scene = this.getScene();
  19277. this._batchCache.mustReturn = false;
  19278. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19279. this._batchCache.visibleInstances[subMeshId] = null;
  19280. if (this._visibleInstances) {
  19281. var currentRenderId = scene.getRenderId();
  19282. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19283. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19284. var selfRenderId = this._renderId;
  19285. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19286. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19287. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19288. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19289. }
  19290. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19291. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19292. this._batchCache.mustReturn = true;
  19293. return this._batchCache;
  19294. }
  19295. if (currentRenderId !== selfRenderId) {
  19296. this._batchCache.renderSelf[subMeshId] = false;
  19297. }
  19298. }
  19299. this._renderIdForInstances[subMeshId] = currentRenderId;
  19300. }
  19301. return this._batchCache;
  19302. };
  19303. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19304. var visibleInstances = batch.visibleInstances[subMesh._id];
  19305. var matricesCount = visibleInstances.length + 1;
  19306. var bufferSize = matricesCount * 16 * 4;
  19307. var currentInstancesBufferSize = this._instancesBufferSize;
  19308. var instancesBuffer = this._instancesBuffer;
  19309. while (this._instancesBufferSize < bufferSize) {
  19310. this._instancesBufferSize *= 2;
  19311. }
  19312. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19313. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  19314. }
  19315. var offset = 0;
  19316. var instancesCount = 0;
  19317. var world = this.getWorldMatrix();
  19318. if (batch.renderSelf[subMesh._id]) {
  19319. world.copyToArray(this._instancesData, offset);
  19320. offset += 16;
  19321. instancesCount++;
  19322. }
  19323. if (visibleInstances) {
  19324. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  19325. var instance = visibleInstances[instanceIndex];
  19326. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  19327. offset += 16;
  19328. instancesCount++;
  19329. }
  19330. }
  19331. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  19332. if (instancesBuffer) {
  19333. instancesBuffer.dispose();
  19334. }
  19335. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  19336. this._instancesBuffer = instancesBuffer;
  19337. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  19338. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  19339. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  19340. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  19341. }
  19342. else {
  19343. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  19344. }
  19345. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  19346. this._draw(subMesh, fillMode, instancesCount);
  19347. engine.unbindInstanceAttributes();
  19348. };
  19349. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  19350. var scene = this.getScene();
  19351. var engine = scene.getEngine();
  19352. if (hardwareInstancedRendering) {
  19353. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  19354. }
  19355. else {
  19356. if (batch.renderSelf[subMesh._id]) {
  19357. // Draw
  19358. if (onBeforeDraw) {
  19359. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  19360. }
  19361. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  19362. }
  19363. if (batch.visibleInstances[subMesh._id]) {
  19364. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  19365. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  19366. // World
  19367. var world = instance.getWorldMatrix();
  19368. if (onBeforeDraw) {
  19369. onBeforeDraw(true, world, effectiveMaterial);
  19370. }
  19371. // Draw
  19372. this._draw(subMesh, fillMode);
  19373. }
  19374. }
  19375. }
  19376. };
  19377. /**
  19378. * Triggers the draw call for the mesh.
  19379. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  19380. */
  19381. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  19382. var scene = this.getScene();
  19383. // Managing instances
  19384. var batch = this._getInstancesRenderList(subMesh._id);
  19385. if (batch.mustReturn) {
  19386. return;
  19387. }
  19388. // Checking geometry state
  19389. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19390. return;
  19391. }
  19392. var callbackIndex;
  19393. this.onBeforeRenderObservable.notifyObservers(this);
  19394. var engine = scene.getEngine();
  19395. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  19396. // Material
  19397. var effectiveMaterial = subMesh.getMaterial();
  19398. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  19399. return;
  19400. }
  19401. // Outline - step 1
  19402. var savedDepthWrite = engine.getDepthWrite();
  19403. if (this.renderOutline) {
  19404. engine.setDepthWrite(false);
  19405. scene.getOutlineRenderer().render(subMesh, batch);
  19406. engine.setDepthWrite(savedDepthWrite);
  19407. }
  19408. effectiveMaterial._preBind();
  19409. var effect = effectiveMaterial.getEffect();
  19410. // Bind
  19411. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  19412. this._bind(subMesh, effect, fillMode);
  19413. var world = this.getWorldMatrix();
  19414. effectiveMaterial.bind(world, this);
  19415. // Alpha mode
  19416. if (enableAlphaMode) {
  19417. engine.setAlphaMode(effectiveMaterial.alphaMode);
  19418. }
  19419. // Draw
  19420. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw);
  19421. // Unbind
  19422. effectiveMaterial.unbind();
  19423. // Outline - step 2
  19424. if (this.renderOutline && savedDepthWrite) {
  19425. engine.setDepthWrite(true);
  19426. engine.setColorWrite(false);
  19427. scene.getOutlineRenderer().render(subMesh, batch);
  19428. engine.setColorWrite(true);
  19429. }
  19430. // Overlay
  19431. if (this.renderOverlay) {
  19432. var currentMode = engine.getAlphaMode();
  19433. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  19434. scene.getOutlineRenderer().render(subMesh, batch, true);
  19435. engine.setAlphaMode(currentMode);
  19436. }
  19437. this.onAfterRenderObservable.notifyObservers(this);
  19438. };
  19439. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  19440. if (isInstance) {
  19441. effectiveMaterial.bindOnlyWorldMatrix(world);
  19442. }
  19443. };
  19444. /**
  19445. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  19446. */
  19447. Mesh.prototype.getEmittedParticleSystems = function () {
  19448. var results = new Array();
  19449. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19450. var particleSystem = this.getScene().particleSystems[index];
  19451. if (particleSystem.emitter === this) {
  19452. results.push(particleSystem);
  19453. }
  19454. }
  19455. return results;
  19456. };
  19457. /**
  19458. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  19459. */
  19460. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  19461. var results = new Array();
  19462. var descendants = this.getDescendants();
  19463. descendants.push(this);
  19464. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  19465. var particleSystem = this.getScene().particleSystems[index];
  19466. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  19467. results.push(particleSystem);
  19468. }
  19469. }
  19470. return results;
  19471. };
  19472. Mesh.prototype._checkDelayState = function () {
  19473. var scene = this.getScene();
  19474. if (this._geometry) {
  19475. this._geometry.load(scene);
  19476. }
  19477. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  19478. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  19479. this._queueLoad(this, scene);
  19480. }
  19481. };
  19482. Mesh.prototype._queueLoad = function (mesh, scene) {
  19483. var _this = this;
  19484. scene._addPendingData(mesh);
  19485. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  19486. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  19487. if (data instanceof ArrayBuffer) {
  19488. _this._delayLoadingFunction(data, _this);
  19489. }
  19490. else {
  19491. _this._delayLoadingFunction(JSON.parse(data), _this);
  19492. }
  19493. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  19494. scene._removePendingData(_this);
  19495. }, function () { }, scene.database, getBinaryData);
  19496. };
  19497. /**
  19498. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  19499. */
  19500. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  19501. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19502. return false;
  19503. }
  19504. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  19505. return false;
  19506. }
  19507. this._checkDelayState();
  19508. return true;
  19509. };
  19510. /**
  19511. * Sets the mesh material by the material or multiMaterial `id` property.
  19512. * The material `id` is a string identifying the material or the multiMaterial.
  19513. * This method returns nothing.
  19514. */
  19515. Mesh.prototype.setMaterialByID = function (id) {
  19516. var materials = this.getScene().materials;
  19517. var index;
  19518. for (index = 0; index < materials.length; index++) {
  19519. if (materials[index].id === id) {
  19520. this.material = materials[index];
  19521. return;
  19522. }
  19523. }
  19524. // Multi
  19525. var multiMaterials = this.getScene().multiMaterials;
  19526. for (index = 0; index < multiMaterials.length; index++) {
  19527. if (multiMaterials[index].id === id) {
  19528. this.material = multiMaterials[index];
  19529. return;
  19530. }
  19531. }
  19532. };
  19533. /**
  19534. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  19535. */
  19536. Mesh.prototype.getAnimatables = function () {
  19537. var results = [];
  19538. if (this.material) {
  19539. results.push(this.material);
  19540. }
  19541. if (this.skeleton) {
  19542. results.push(this.skeleton);
  19543. }
  19544. return results;
  19545. };
  19546. /**
  19547. * Modifies the mesh geometry according to the passed transformation matrix.
  19548. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  19549. * The mesh normals are modified accordingly the same transformation.
  19550. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19551. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19552. */
  19553. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  19554. // Position
  19555. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19556. return;
  19557. }
  19558. var submeshes = this.subMeshes.splice(0);
  19559. this._resetPointsArrayCache();
  19560. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19561. var temp = [];
  19562. var index;
  19563. for (index = 0; index < data.length; index += 3) {
  19564. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  19565. }
  19566. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  19567. // Normals
  19568. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19569. return;
  19570. }
  19571. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19572. temp = [];
  19573. for (index = 0; index < data.length; index += 3) {
  19574. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  19575. }
  19576. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  19577. // flip faces?
  19578. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  19579. this.flipFaces();
  19580. }
  19581. // Restore submeshes
  19582. this.releaseSubMeshes();
  19583. this.subMeshes = submeshes;
  19584. };
  19585. /**
  19586. * Modifies the mesh geometry according to its own current World Matrix.
  19587. * The mesh World Matrix is then reset.
  19588. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  19589. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  19590. * Note that, under the hood, this method sets a new VertexBuffer each call.
  19591. */
  19592. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  19593. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  19594. this.scaling.copyFromFloats(1, 1, 1);
  19595. this.position.copyFromFloats(0, 0, 0);
  19596. this.rotation.copyFromFloats(0, 0, 0);
  19597. //only if quaternion is already set
  19598. if (this.rotationQuaternion) {
  19599. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  19600. }
  19601. this._worldMatrix = BABYLON.Matrix.Identity();
  19602. };
  19603. // Cache
  19604. Mesh.prototype._resetPointsArrayCache = function () {
  19605. this._positions = null;
  19606. };
  19607. Mesh.prototype._generatePointsArray = function () {
  19608. if (this._positions)
  19609. return true;
  19610. this._positions = [];
  19611. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19612. if (!data) {
  19613. return false;
  19614. }
  19615. for (var index = 0; index < data.length; index += 3) {
  19616. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  19617. }
  19618. return true;
  19619. };
  19620. /**
  19621. * Returns a new Mesh object generated from the current mesh properties.
  19622. * This method must not get confused with createInstance().
  19623. * The parameter `name` is a string, the name given to the new mesh.
  19624. * The optional parameter `newParent` can be any Node object (default `null`).
  19625. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  19626. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  19627. */
  19628. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  19629. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19630. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  19631. };
  19632. /**
  19633. * Disposes the mesh.
  19634. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  19635. */
  19636. Mesh.prototype.dispose = function (doNotRecurse) {
  19637. if (this._geometry) {
  19638. this._geometry.releaseForMesh(this, true);
  19639. }
  19640. // Instances
  19641. if (this._instancesBuffer) {
  19642. this._instancesBuffer.dispose();
  19643. this._instancesBuffer = null;
  19644. }
  19645. while (this.instances.length) {
  19646. this.instances[0].dispose();
  19647. }
  19648. _super.prototype.dispose.call(this, doNotRecurse);
  19649. };
  19650. /**
  19651. * Modifies the mesh geometry according to a displacement map.
  19652. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  19653. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19654. * This method returns nothing.
  19655. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  19656. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19657. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  19658. */
  19659. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  19660. var _this = this;
  19661. var scene = this.getScene();
  19662. var onload = function (img) {
  19663. // Getting height map data
  19664. var canvas = document.createElement("canvas");
  19665. var context = canvas.getContext("2d");
  19666. var heightMapWidth = img.width;
  19667. var heightMapHeight = img.height;
  19668. canvas.width = heightMapWidth;
  19669. canvas.height = heightMapHeight;
  19670. context.drawImage(img, 0, 0);
  19671. // Create VertexData from map data
  19672. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  19673. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  19674. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  19675. //execute success callback, if set
  19676. if (onSuccess) {
  19677. onSuccess(_this);
  19678. }
  19679. };
  19680. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  19681. };
  19682. /**
  19683. * Modifies the mesh geometry according to a displacementMap buffer.
  19684. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  19685. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  19686. * This method returns nothing.
  19687. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  19688. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  19689. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  19690. */
  19691. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  19692. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  19693. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  19694. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19695. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  19696. return;
  19697. }
  19698. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19699. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19700. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19701. var position = BABYLON.Vector3.Zero();
  19702. var normal = BABYLON.Vector3.Zero();
  19703. var uv = BABYLON.Vector2.Zero();
  19704. for (var index = 0; index < positions.length; index += 3) {
  19705. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  19706. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  19707. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  19708. // Compute height
  19709. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  19710. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  19711. var pos = (u + v * heightMapWidth) * 4;
  19712. var r = buffer[pos] / 255.0;
  19713. var g = buffer[pos + 1] / 255.0;
  19714. var b = buffer[pos + 2] / 255.0;
  19715. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  19716. normal.normalize();
  19717. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  19718. position = position.add(normal);
  19719. position.toArray(positions, index);
  19720. }
  19721. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  19722. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  19723. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19724. };
  19725. /**
  19726. * Modify the mesh to get a flat shading rendering.
  19727. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  19728. * This method returns nothing.
  19729. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  19730. */
  19731. Mesh.prototype.convertToFlatShadedMesh = function () {
  19732. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  19733. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19734. var kinds = this.getVerticesDataKinds();
  19735. var vbs = [];
  19736. var data = [];
  19737. var newdata = [];
  19738. var updatableNormals = false;
  19739. var kindIndex;
  19740. var kind;
  19741. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19742. kind = kinds[kindIndex];
  19743. var vertexBuffer = this.getVertexBuffer(kind);
  19744. if (kind === BABYLON.VertexBuffer.NormalKind) {
  19745. updatableNormals = vertexBuffer.isUpdatable();
  19746. kinds.splice(kindIndex, 1);
  19747. kindIndex--;
  19748. continue;
  19749. }
  19750. vbs[kind] = vertexBuffer;
  19751. data[kind] = vbs[kind].getData();
  19752. newdata[kind] = [];
  19753. }
  19754. // Save previous submeshes
  19755. var previousSubmeshes = this.subMeshes.slice(0);
  19756. var indices = this.getIndices();
  19757. var totalIndices = this.getTotalIndices();
  19758. // Generating unique vertices per face
  19759. var index;
  19760. for (index = 0; index < totalIndices; index++) {
  19761. var vertexIndex = indices[index];
  19762. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19763. kind = kinds[kindIndex];
  19764. var stride = vbs[kind].getStrideSize();
  19765. for (var offset = 0; offset < stride; offset++) {
  19766. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19767. }
  19768. }
  19769. }
  19770. // Updating faces & normal
  19771. var normals = [];
  19772. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  19773. for (index = 0; index < totalIndices; index += 3) {
  19774. indices[index] = index;
  19775. indices[index + 1] = index + 1;
  19776. indices[index + 2] = index + 2;
  19777. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  19778. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  19779. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  19780. var p1p2 = p1.subtract(p2);
  19781. var p3p2 = p3.subtract(p2);
  19782. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  19783. // Store same normals for every vertex
  19784. for (var localIndex = 0; localIndex < 3; localIndex++) {
  19785. normals.push(normal.x);
  19786. normals.push(normal.y);
  19787. normals.push(normal.z);
  19788. }
  19789. }
  19790. this.setIndices(indices);
  19791. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  19792. // Updating vertex buffers
  19793. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19794. kind = kinds[kindIndex];
  19795. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19796. }
  19797. // Updating submeshes
  19798. this.releaseSubMeshes();
  19799. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19800. var previousOne = previousSubmeshes[submeshIndex];
  19801. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19802. }
  19803. this.synchronizeInstances();
  19804. };
  19805. /**
  19806. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  19807. * In other words, more vertices, no more indices and a single bigger VBO.
  19808. * This method returns nothing.
  19809. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  19810. *
  19811. */
  19812. Mesh.prototype.convertToUnIndexedMesh = function () {
  19813. /// <summary>Remove indices by unfolding faces into buffers</summary>
  19814. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  19815. var kinds = this.getVerticesDataKinds();
  19816. var vbs = [];
  19817. var data = [];
  19818. var newdata = [];
  19819. var updatableNormals = false;
  19820. var kindIndex;
  19821. var kind;
  19822. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19823. kind = kinds[kindIndex];
  19824. var vertexBuffer = this.getVertexBuffer(kind);
  19825. vbs[kind] = vertexBuffer;
  19826. data[kind] = vbs[kind].getData();
  19827. newdata[kind] = [];
  19828. }
  19829. // Save previous submeshes
  19830. var previousSubmeshes = this.subMeshes.slice(0);
  19831. var indices = this.getIndices();
  19832. var totalIndices = this.getTotalIndices();
  19833. // Generating unique vertices per face
  19834. var index;
  19835. for (index = 0; index < totalIndices; index++) {
  19836. var vertexIndex = indices[index];
  19837. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19838. kind = kinds[kindIndex];
  19839. var stride = vbs[kind].getStrideSize();
  19840. for (var offset = 0; offset < stride; offset++) {
  19841. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  19842. }
  19843. }
  19844. }
  19845. // Updating indices
  19846. for (index = 0; index < totalIndices; index += 3) {
  19847. indices[index] = index;
  19848. indices[index + 1] = index + 1;
  19849. indices[index + 2] = index + 2;
  19850. }
  19851. this.setIndices(indices);
  19852. // Updating vertex buffers
  19853. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  19854. kind = kinds[kindIndex];
  19855. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  19856. }
  19857. // Updating submeshes
  19858. this.releaseSubMeshes();
  19859. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  19860. var previousOne = previousSubmeshes[submeshIndex];
  19861. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  19862. }
  19863. this._unIndexed = true;
  19864. this.synchronizeInstances();
  19865. };
  19866. /**
  19867. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  19868. * This method returns nothing.
  19869. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  19870. */
  19871. Mesh.prototype.flipFaces = function (flipNormals) {
  19872. if (flipNormals === void 0) { flipNormals = false; }
  19873. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  19874. var i;
  19875. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19876. for (i = 0; i < vertex_data.normals.length; i++) {
  19877. vertex_data.normals[i] *= -1;
  19878. }
  19879. }
  19880. var temp;
  19881. for (i = 0; i < vertex_data.indices.length; i += 3) {
  19882. // reassign indices
  19883. temp = vertex_data.indices[i + 1];
  19884. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  19885. vertex_data.indices[i + 2] = temp;
  19886. }
  19887. vertex_data.applyToMesh(this);
  19888. };
  19889. // Instances
  19890. /**
  19891. * Creates a new InstancedMesh object from the mesh model.
  19892. * An instance shares the same properties and the same material than its model.
  19893. * Only these properties of each instance can then be set individually :
  19894. * - position
  19895. * - rotation
  19896. * - rotationQuaternion
  19897. * - setPivotMatrix
  19898. * - scaling
  19899. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  19900. * Warning : this method is not supported for Line mesh and LineSystem
  19901. */
  19902. Mesh.prototype.createInstance = function (name) {
  19903. return new BABYLON.InstancedMesh(name, this);
  19904. };
  19905. /**
  19906. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  19907. * After this call, all the mesh instances have the same submeshes than the current mesh.
  19908. * This method returns nothing.
  19909. */
  19910. Mesh.prototype.synchronizeInstances = function () {
  19911. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  19912. var instance = this.instances[instanceIndex];
  19913. instance._syncSubMeshes();
  19914. }
  19915. };
  19916. /**
  19917. * Simplify the mesh according to the given array of settings.
  19918. * Function will return immediately and will simplify async. It returns nothing.
  19919. * @param settings a collection of simplification settings.
  19920. * @param parallelProcessing should all levels calculate parallel or one after the other.
  19921. * @param type the type of simplification to run.
  19922. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  19923. */
  19924. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  19925. if (parallelProcessing === void 0) { parallelProcessing = true; }
  19926. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  19927. this.getScene().simplificationQueue.addTask({
  19928. settings: settings,
  19929. parallelProcessing: parallelProcessing,
  19930. mesh: this,
  19931. simplificationType: simplificationType,
  19932. successCallback: successCallback
  19933. });
  19934. };
  19935. /**
  19936. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  19937. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  19938. * This should be used together with the simplification to avoid disappearing triangles.
  19939. * @param successCallback an optional success callback to be called after the optimization finished.
  19940. */
  19941. Mesh.prototype.optimizeIndices = function (successCallback) {
  19942. var _this = this;
  19943. var indices = this.getIndices();
  19944. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19945. var vectorPositions = [];
  19946. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  19947. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  19948. }
  19949. var dupes = [];
  19950. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  19951. var realPos = vectorPositions.length - 1 - iteration;
  19952. var testedPosition = vectorPositions[realPos];
  19953. for (var j = 0; j < realPos; ++j) {
  19954. var againstPosition = vectorPositions[j];
  19955. if (testedPosition.equals(againstPosition)) {
  19956. dupes[realPos] = j;
  19957. break;
  19958. }
  19959. }
  19960. }, function () {
  19961. for (var i = 0; i < indices.length; ++i) {
  19962. indices[i] = dupes[indices[i]] || indices[i];
  19963. }
  19964. //indices are now reordered
  19965. var originalSubMeshes = _this.subMeshes.slice(0);
  19966. _this.setIndices(indices);
  19967. _this.subMeshes = originalSubMeshes;
  19968. if (successCallback) {
  19969. successCallback(_this);
  19970. }
  19971. });
  19972. };
  19973. // Statics
  19974. /**
  19975. * Returns a new Mesh object what is a deep copy of the passed mesh.
  19976. * The parameter `parsedMesh` is the mesh to be copied.
  19977. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19978. */
  19979. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  19980. var mesh = new Mesh(parsedMesh.name, scene);
  19981. mesh.id = parsedMesh.id;
  19982. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19983. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19984. if (parsedMesh.rotationQuaternion) {
  19985. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19986. }
  19987. else if (parsedMesh.rotation) {
  19988. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19989. }
  19990. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19991. if (parsedMesh.localMatrix) {
  19992. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19993. }
  19994. else if (parsedMesh.pivotMatrix) {
  19995. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19996. }
  19997. mesh.setEnabled(parsedMesh.isEnabled);
  19998. mesh.isVisible = parsedMesh.isVisible;
  19999. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20000. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20001. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20002. if (parsedMesh.applyFog !== undefined) {
  20003. mesh.applyFog = parsedMesh.applyFog;
  20004. }
  20005. if (parsedMesh.pickable !== undefined) {
  20006. mesh.isPickable = parsedMesh.pickable;
  20007. }
  20008. if (parsedMesh.alphaIndex !== undefined) {
  20009. mesh.alphaIndex = parsedMesh.alphaIndex;
  20010. }
  20011. mesh.receiveShadows = parsedMesh.receiveShadows;
  20012. mesh.billboardMode = parsedMesh.billboardMode;
  20013. if (parsedMesh.visibility !== undefined) {
  20014. mesh.visibility = parsedMesh.visibility;
  20015. }
  20016. mesh.checkCollisions = parsedMesh.checkCollisions;
  20017. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20018. // freezeWorldMatrix
  20019. if (parsedMesh.freezeWorldMatrix) {
  20020. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20021. }
  20022. // Parent
  20023. if (parsedMesh.parentId) {
  20024. mesh._waitingParentId = parsedMesh.parentId;
  20025. }
  20026. // Actions
  20027. if (parsedMesh.actions !== undefined) {
  20028. mesh._waitingActions = parsedMesh.actions;
  20029. }
  20030. // Geometry
  20031. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20032. if (parsedMesh.delayLoadingFile) {
  20033. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20034. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20035. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20036. if (parsedMesh._binaryInfo) {
  20037. mesh._binaryInfo = parsedMesh._binaryInfo;
  20038. }
  20039. mesh._delayInfo = [];
  20040. if (parsedMesh.hasUVs) {
  20041. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20042. }
  20043. if (parsedMesh.hasUVs2) {
  20044. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20045. }
  20046. if (parsedMesh.hasUVs3) {
  20047. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20048. }
  20049. if (parsedMesh.hasUVs4) {
  20050. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20051. }
  20052. if (parsedMesh.hasUVs5) {
  20053. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20054. }
  20055. if (parsedMesh.hasUVs6) {
  20056. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20057. }
  20058. if (parsedMesh.hasColors) {
  20059. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20060. }
  20061. if (parsedMesh.hasMatricesIndices) {
  20062. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20063. }
  20064. if (parsedMesh.hasMatricesWeights) {
  20065. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20066. }
  20067. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20068. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20069. mesh._checkDelayState();
  20070. }
  20071. }
  20072. else {
  20073. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20074. }
  20075. // Material
  20076. if (parsedMesh.materialId) {
  20077. mesh.setMaterialByID(parsedMesh.materialId);
  20078. }
  20079. else {
  20080. mesh.material = null;
  20081. }
  20082. // Skeleton
  20083. if (parsedMesh.skeletonId > -1) {
  20084. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20085. if (parsedMesh.numBoneInfluencers) {
  20086. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20087. }
  20088. }
  20089. // Animations
  20090. if (parsedMesh.animations) {
  20091. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20092. var parsedAnimation = parsedMesh.animations[animationIndex];
  20093. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20094. }
  20095. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20096. }
  20097. if (parsedMesh.autoAnimate) {
  20098. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20099. }
  20100. // Layer Mask
  20101. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20102. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20103. }
  20104. else {
  20105. mesh.layerMask = 0x0FFFFFFF;
  20106. }
  20107. //(Deprecated) physics
  20108. if (parsedMesh.physicsImpostor) {
  20109. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20110. mass: parsedMesh.physicsMass,
  20111. friction: parsedMesh.physicsFriction,
  20112. restitution: parsedMesh.physicsRestitution
  20113. }, scene);
  20114. }
  20115. // Instances
  20116. if (parsedMesh.instances) {
  20117. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20118. var parsedInstance = parsedMesh.instances[index];
  20119. var instance = mesh.createInstance(parsedInstance.name);
  20120. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20121. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20122. if (parsedInstance.rotationQuaternion) {
  20123. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20124. }
  20125. else if (parsedInstance.rotation) {
  20126. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20127. }
  20128. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20129. instance.checkCollisions = mesh.checkCollisions;
  20130. if (parsedMesh.animations) {
  20131. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20132. parsedAnimation = parsedMesh.animations[animationIndex];
  20133. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20134. }
  20135. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20136. }
  20137. }
  20138. }
  20139. return mesh;
  20140. };
  20141. /**
  20142. * Creates a ribbon mesh.
  20143. * Please consider using the same method from the MeshBuilder class instead.
  20144. * 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.
  20145. *
  20146. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20147. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20148. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20149. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20150. * 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.
  20151. * 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.
  20152. * 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
  20153. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20154. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20155. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20156. */
  20157. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20158. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20159. pathArray: pathArray,
  20160. closeArray: closeArray,
  20161. closePath: closePath,
  20162. offset: offset,
  20163. updatable: updatable,
  20164. sideOrientation: sideOrientation,
  20165. instance: instance
  20166. }, scene);
  20167. };
  20168. /**
  20169. * Creates a plane polygonal mesh. By default, this is a disc.
  20170. * Please consider using the same method from the MeshBuilder class instead.
  20171. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20172. * 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.
  20173. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20174. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20175. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20176. */
  20177. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20178. var options = {
  20179. radius: radius,
  20180. tessellation: tessellation,
  20181. sideOrientation: sideOrientation,
  20182. updatable: updatable
  20183. };
  20184. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20185. };
  20186. /**
  20187. * Creates a box mesh.
  20188. * Please consider using the same method from the MeshBuilder class instead.
  20189. * The parameter `size` sets the size (float) of each box side (default 1).
  20190. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20191. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20192. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20193. */
  20194. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20195. var options = {
  20196. size: size,
  20197. sideOrientation: sideOrientation,
  20198. updatable: updatable
  20199. };
  20200. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20201. };
  20202. /**
  20203. * Creates a sphere mesh.
  20204. * Please consider using the same method from the MeshBuilder class instead.
  20205. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20206. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20207. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20208. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20210. */
  20211. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20212. var options = {
  20213. segments: segments,
  20214. diameterX: diameter,
  20215. diameterY: diameter,
  20216. diameterZ: diameter,
  20217. sideOrientation: sideOrientation,
  20218. updatable: updatable
  20219. };
  20220. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20221. };
  20222. /**
  20223. * Creates a cylinder or a cone mesh.
  20224. * Please consider using the same method from the MeshBuilder class instead.
  20225. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20226. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20227. * 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.
  20228. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20229. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20230. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20231. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20232. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20233. */
  20234. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20235. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20236. if (scene !== undefined) {
  20237. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20238. updatable = scene;
  20239. }
  20240. scene = subdivisions;
  20241. subdivisions = 1;
  20242. }
  20243. var options = {
  20244. height: height,
  20245. diameterTop: diameterTop,
  20246. diameterBottom: diameterBottom,
  20247. tessellation: tessellation,
  20248. subdivisions: subdivisions,
  20249. sideOrientation: sideOrientation,
  20250. updatable: updatable
  20251. };
  20252. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20253. };
  20254. // Torus (Code from SharpDX.org)
  20255. /**
  20256. * Creates a torus mesh.
  20257. * Please consider using the same method from the MeshBuilder class instead.
  20258. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20259. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20260. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20261. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20262. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20264. */
  20265. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20266. var options = {
  20267. diameter: diameter,
  20268. thickness: thickness,
  20269. tessellation: tessellation,
  20270. sideOrientation: sideOrientation,
  20271. updatable: updatable
  20272. };
  20273. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20274. };
  20275. /**
  20276. * Creates a torus knot mesh.
  20277. * Please consider using the same method from the MeshBuilder class instead.
  20278. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20279. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20280. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20281. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20282. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20283. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20284. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20285. */
  20286. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20287. var options = {
  20288. radius: radius,
  20289. tube: tube,
  20290. radialSegments: radialSegments,
  20291. tubularSegments: tubularSegments,
  20292. p: p,
  20293. q: q,
  20294. sideOrientation: sideOrientation,
  20295. updatable: updatable
  20296. };
  20297. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20298. };
  20299. /**
  20300. * Creates a line mesh.
  20301. * Please consider using the same method from the MeshBuilder class instead.
  20302. * 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.
  20303. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20304. * The parameter `points` is an array successive Vector3.
  20305. * 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
  20306. * When updating an instance, remember that only point positions can change, not the number of points.
  20307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20308. */
  20309. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  20310. var options = {
  20311. points: points,
  20312. updatable: updatable,
  20313. instance: instance
  20314. };
  20315. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  20316. };
  20317. /**
  20318. * Creates a dashed line mesh.
  20319. * Please consider using the same method from the MeshBuilder class instead.
  20320. * 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.
  20321. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  20322. * The parameter `points` is an array successive Vector3.
  20323. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  20324. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  20325. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  20326. * 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
  20327. * When updating an instance, remember that only point positions can change, not the number of points.
  20328. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20329. */
  20330. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  20331. var options = {
  20332. points: points,
  20333. dashSize: dashSize,
  20334. gapSize: gapSize,
  20335. dashNb: dashNb,
  20336. updatable: updatable,
  20337. instance: instance
  20338. };
  20339. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  20340. };
  20341. /**
  20342. * Creates an extruded shape mesh.
  20343. * 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.
  20344. * Please consider using the same method from the MeshBuilder class instead.
  20345. *
  20346. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20347. * 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
  20348. * extruded along the Z axis.
  20349. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20350. * 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.
  20351. * The parameter `scale` (float, default 1) is the value to scale the shape.
  20352. * 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
  20353. * 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
  20354. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20355. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20356. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20357. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20358. */
  20359. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  20360. var options = {
  20361. shape: shape,
  20362. path: path,
  20363. scale: scale,
  20364. rotation: rotation,
  20365. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20366. sideOrientation: sideOrientation,
  20367. instance: instance,
  20368. updatable: updatable
  20369. };
  20370. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  20371. };
  20372. /**
  20373. * Creates an custom extruded shape mesh.
  20374. * 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.
  20375. * Please consider using the same method from the MeshBuilder class instead.
  20376. *
  20377. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  20378. * 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
  20379. * extruded along the Z axis.
  20380. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  20381. * 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
  20382. * and the distance of this point from the begining of the path :
  20383. * ```javascript
  20384. * var rotationFunction = function(i, distance) {
  20385. * // do things
  20386. * return rotationValue; }
  20387. * ```
  20388. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  20389. * 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
  20390. * and the distance of this point from the begining of the path :
  20391. * ```javascript
  20392. * var scaleFunction = function(i, distance) {
  20393. * // do things
  20394. * return scaleValue;}
  20395. * ```
  20396. * It must returns a float value that will be the scale value applied to the shape on each path point.
  20397. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  20398. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  20399. * 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
  20400. * 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
  20401. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  20402. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20403. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20404. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20405. */
  20406. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  20407. var options = {
  20408. shape: shape,
  20409. path: path,
  20410. scaleFunction: scaleFunction,
  20411. rotationFunction: rotationFunction,
  20412. ribbonCloseArray: ribbonCloseArray,
  20413. ribbonClosePath: ribbonClosePath,
  20414. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  20415. sideOrientation: sideOrientation,
  20416. instance: instance,
  20417. updatable: updatable
  20418. };
  20419. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  20420. };
  20421. /**
  20422. * Creates lathe mesh.
  20423. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  20424. * Please consider using the same method from the MeshBuilder class instead.
  20425. * 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
  20426. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  20427. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  20428. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  20429. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20430. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20431. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20432. */
  20433. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  20434. var options = {
  20435. shape: shape,
  20436. radius: radius,
  20437. tessellation: tessellation,
  20438. sideOrientation: sideOrientation,
  20439. updatable: updatable
  20440. };
  20441. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  20442. };
  20443. /**
  20444. * Creates a plane mesh.
  20445. * Please consider using the same method from the MeshBuilder class instead.
  20446. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  20447. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20448. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20449. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20450. */
  20451. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  20452. var options = {
  20453. size: size,
  20454. width: size,
  20455. height: size,
  20456. sideOrientation: sideOrientation,
  20457. updatable: updatable
  20458. };
  20459. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  20460. };
  20461. /**
  20462. * Creates a ground mesh.
  20463. * Please consider using the same method from the MeshBuilder class instead.
  20464. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  20465. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  20466. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20467. */
  20468. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  20469. var options = {
  20470. width: width,
  20471. height: height,
  20472. subdivisions: subdivisions,
  20473. updatable: updatable
  20474. };
  20475. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  20476. };
  20477. /**
  20478. * Creates a tiled ground mesh.
  20479. * Please consider using the same method from the MeshBuilder class instead.
  20480. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  20481. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  20482. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  20483. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  20484. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  20485. * numbers of subdivisions on the ground width and height of each tile.
  20486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20487. */
  20488. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  20489. var options = {
  20490. xmin: xmin,
  20491. zmin: zmin,
  20492. xmax: xmax,
  20493. zmax: zmax,
  20494. subdivisions: subdivisions,
  20495. precision: precision,
  20496. updatable: updatable
  20497. };
  20498. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  20499. };
  20500. /**
  20501. * Creates a ground mesh from a height map.
  20502. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  20503. * Please consider using the same method from the MeshBuilder class instead.
  20504. * The parameter `url` sets the URL of the height map image resource.
  20505. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  20506. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  20507. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  20508. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  20509. * 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).
  20510. * This function is passed the newly built mesh :
  20511. * ```javascript
  20512. * function(mesh) { // do things
  20513. * return; }
  20514. * ```
  20515. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20516. */
  20517. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  20518. var options = {
  20519. width: width,
  20520. height: height,
  20521. subdivisions: subdivisions,
  20522. minHeight: minHeight,
  20523. maxHeight: maxHeight,
  20524. updatable: updatable,
  20525. onReady: onReady
  20526. };
  20527. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  20528. };
  20529. /**
  20530. * Creates a tube mesh.
  20531. * 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.
  20532. * Please consider using the same method from the MeshBuilder class instead.
  20533. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  20534. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  20535. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  20536. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  20537. * 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.
  20538. * It must return a radius value (positive float) :
  20539. * ```javascript
  20540. * var radiusFunction = function(i, distance) {
  20541. * // do things
  20542. * return radius; }
  20543. * ```
  20544. * 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
  20545. * 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
  20546. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20547. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20548. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20549. */
  20550. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  20551. var options = {
  20552. path: path,
  20553. radius: radius,
  20554. tessellation: tessellation,
  20555. radiusFunction: radiusFunction,
  20556. arc: 1,
  20557. cap: cap,
  20558. updatable: updatable,
  20559. sideOrientation: sideOrientation,
  20560. instance: instance
  20561. };
  20562. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  20563. };
  20564. /**
  20565. * Creates a polyhedron mesh.
  20566. * Please consider using the same method from the MeshBuilder class instead.
  20567. * 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
  20568. * to choose the wanted type.
  20569. * The parameter `size` (positive float, default 1) sets the polygon size.
  20570. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  20571. * 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`.
  20572. * 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
  20573. * 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)`).
  20574. * 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
  20575. * 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.
  20576. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20577. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20578. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20579. */
  20580. Mesh.CreatePolyhedron = function (name, options, scene) {
  20581. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  20582. };
  20583. /**
  20584. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  20585. * Please consider using the same method from the MeshBuilder class instead.
  20586. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  20587. * 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`).
  20588. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  20589. * 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.
  20590. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20591. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20592. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20593. */
  20594. Mesh.CreateIcoSphere = function (name, options, scene) {
  20595. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  20596. };
  20597. /**
  20598. * Creates a decal mesh.
  20599. * Please consider using the same method from the MeshBuilder class instead.
  20600. * 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.
  20601. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  20602. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  20603. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  20604. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  20605. */
  20606. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  20607. var options = {
  20608. position: position,
  20609. normal: normal,
  20610. size: size,
  20611. angle: angle
  20612. };
  20613. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  20614. };
  20615. // Skeletons
  20616. /**
  20617. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20618. */
  20619. Mesh.prototype.setPositionsForCPUSkinning = function () {
  20620. var source;
  20621. if (!this._sourcePositions) {
  20622. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20623. this._sourcePositions = new Float32Array(source);
  20624. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  20625. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  20626. }
  20627. }
  20628. return this._sourcePositions;
  20629. };
  20630. /**
  20631. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  20632. */
  20633. Mesh.prototype.setNormalsForCPUSkinning = function () {
  20634. var source;
  20635. if (!this._sourceNormals) {
  20636. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20637. this._sourceNormals = new Float32Array(source);
  20638. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  20639. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  20640. }
  20641. }
  20642. return this._sourceNormals;
  20643. };
  20644. /**
  20645. * Update the vertex buffers by applying transformation from the bones
  20646. * @param {skeleton} skeleton to apply
  20647. */
  20648. Mesh.prototype.applySkeleton = function (skeleton) {
  20649. if (!this.geometry) {
  20650. return;
  20651. }
  20652. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  20653. return;
  20654. }
  20655. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  20656. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20657. return this;
  20658. }
  20659. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20660. return this;
  20661. }
  20662. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20663. return this;
  20664. }
  20665. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20666. return this;
  20667. }
  20668. if (!this._sourcePositions) {
  20669. this.setPositionsForCPUSkinning();
  20670. }
  20671. if (!this._sourceNormals) {
  20672. this.setNormalsForCPUSkinning();
  20673. }
  20674. // positionsData checks for not being Float32Array will only pass at most once
  20675. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20676. if (!(positionsData instanceof Float32Array)) {
  20677. positionsData = new Float32Array(positionsData);
  20678. }
  20679. // normalsData checks for not being Float32Array will only pass at most once
  20680. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20681. if (!(normalsData instanceof Float32Array)) {
  20682. normalsData = new Float32Array(normalsData);
  20683. }
  20684. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20685. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20686. var needExtras = this.numBoneInfluencers > 4;
  20687. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  20688. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  20689. var skeletonMatrices = skeleton.getTransformMatrices(this);
  20690. var tempVector3 = BABYLON.Vector3.Zero();
  20691. var finalMatrix = new BABYLON.Matrix();
  20692. var tempMatrix = new BABYLON.Matrix();
  20693. var matWeightIdx = 0;
  20694. var inf;
  20695. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  20696. var weight;
  20697. for (inf = 0; inf < 4; inf++) {
  20698. weight = matricesWeightsData[matWeightIdx + inf];
  20699. if (weight > 0) {
  20700. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20701. finalMatrix.addToSelf(tempMatrix);
  20702. }
  20703. else
  20704. break;
  20705. }
  20706. if (needExtras) {
  20707. for (inf = 0; inf < 4; inf++) {
  20708. weight = matricesWeightsExtraData[matWeightIdx + inf];
  20709. if (weight > 0) {
  20710. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  20711. finalMatrix.addToSelf(tempMatrix);
  20712. }
  20713. else
  20714. break;
  20715. }
  20716. }
  20717. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  20718. tempVector3.toArray(positionsData, index);
  20719. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  20720. tempVector3.toArray(normalsData, index);
  20721. finalMatrix.reset();
  20722. }
  20723. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  20724. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  20725. return this;
  20726. };
  20727. // Tools
  20728. /**
  20729. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  20730. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  20731. */
  20732. Mesh.MinMax = function (meshes) {
  20733. var minVector = null;
  20734. var maxVector = null;
  20735. for (var i in meshes) {
  20736. var mesh = meshes[i];
  20737. var boundingBox = mesh.getBoundingInfo().boundingBox;
  20738. if (!minVector) {
  20739. minVector = boundingBox.minimumWorld;
  20740. maxVector = boundingBox.maximumWorld;
  20741. continue;
  20742. }
  20743. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  20744. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  20745. }
  20746. return {
  20747. min: minVector,
  20748. max: maxVector
  20749. };
  20750. };
  20751. /**
  20752. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  20753. */
  20754. Mesh.Center = function (meshesOrMinMaxVector) {
  20755. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  20756. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  20757. };
  20758. /**
  20759. * Merge the array of meshes into a single mesh for performance reasons.
  20760. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  20761. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  20762. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  20763. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  20764. */
  20765. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  20766. if (disposeSource === void 0) { disposeSource = true; }
  20767. var index;
  20768. if (!allow32BitsIndices) {
  20769. var totalVertices = 0;
  20770. // Counting vertices
  20771. for (index = 0; index < meshes.length; index++) {
  20772. if (meshes[index]) {
  20773. totalVertices += meshes[index].getTotalVertices();
  20774. if (totalVertices > 65536) {
  20775. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  20776. return null;
  20777. }
  20778. }
  20779. }
  20780. }
  20781. // Merge
  20782. var vertexData;
  20783. var otherVertexData;
  20784. var source;
  20785. for (index = 0; index < meshes.length; index++) {
  20786. if (meshes[index]) {
  20787. meshes[index].computeWorldMatrix(true);
  20788. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  20789. otherVertexData.transform(meshes[index].getWorldMatrix());
  20790. if (vertexData) {
  20791. vertexData.merge(otherVertexData);
  20792. }
  20793. else {
  20794. vertexData = otherVertexData;
  20795. source = meshes[index];
  20796. }
  20797. }
  20798. }
  20799. if (!meshSubclass) {
  20800. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  20801. }
  20802. vertexData.applyToMesh(meshSubclass);
  20803. // Setting properties
  20804. meshSubclass.material = source.material;
  20805. meshSubclass.checkCollisions = source.checkCollisions;
  20806. // Cleaning
  20807. if (disposeSource) {
  20808. for (index = 0; index < meshes.length; index++) {
  20809. if (meshes[index]) {
  20810. meshes[index].dispose();
  20811. }
  20812. }
  20813. }
  20814. return meshSubclass;
  20815. };
  20816. // Consts
  20817. Mesh._FRONTSIDE = 0;
  20818. Mesh._BACKSIDE = 1;
  20819. Mesh._DOUBLESIDE = 2;
  20820. Mesh._DEFAULTSIDE = 0;
  20821. Mesh._NO_CAP = 0;
  20822. Mesh._CAP_START = 1;
  20823. Mesh._CAP_END = 2;
  20824. Mesh._CAP_ALL = 3;
  20825. return Mesh;
  20826. }(BABYLON.AbstractMesh));
  20827. BABYLON.Mesh = Mesh;
  20828. })(BABYLON || (BABYLON = {}));
  20829. var BABYLON;
  20830. (function (BABYLON) {
  20831. var SubMesh = (function () {
  20832. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  20833. if (createBoundingBox === void 0) { createBoundingBox = true; }
  20834. this.materialIndex = materialIndex;
  20835. this.verticesStart = verticesStart;
  20836. this.verticesCount = verticesCount;
  20837. this.indexStart = indexStart;
  20838. this.indexCount = indexCount;
  20839. this._renderId = 0;
  20840. this._mesh = mesh;
  20841. this._renderingMesh = renderingMesh || mesh;
  20842. mesh.subMeshes.push(this);
  20843. this._trianglePlanes = [];
  20844. this._id = mesh.subMeshes.length - 1;
  20845. if (createBoundingBox) {
  20846. this.refreshBoundingInfo();
  20847. mesh.computeWorldMatrix(true);
  20848. }
  20849. }
  20850. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  20851. get: function () {
  20852. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  20853. },
  20854. enumerable: true,
  20855. configurable: true
  20856. });
  20857. SubMesh.prototype.getBoundingInfo = function () {
  20858. if (this.IsGlobal) {
  20859. return this._mesh.getBoundingInfo();
  20860. }
  20861. return this._boundingInfo;
  20862. };
  20863. SubMesh.prototype.getMesh = function () {
  20864. return this._mesh;
  20865. };
  20866. SubMesh.prototype.getRenderingMesh = function () {
  20867. return this._renderingMesh;
  20868. };
  20869. SubMesh.prototype.getMaterial = function () {
  20870. var rootMaterial = this._renderingMesh.material;
  20871. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  20872. var multiMaterial = rootMaterial;
  20873. return multiMaterial.getSubMaterial(this.materialIndex);
  20874. }
  20875. if (!rootMaterial) {
  20876. return this._mesh.getScene().defaultMaterial;
  20877. }
  20878. return rootMaterial;
  20879. };
  20880. // Methods
  20881. SubMesh.prototype.refreshBoundingInfo = function () {
  20882. this._lastColliderWorldVertices = null;
  20883. if (this.IsGlobal) {
  20884. return;
  20885. }
  20886. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20887. if (!data) {
  20888. this._boundingInfo = this._mesh._boundingInfo;
  20889. return;
  20890. }
  20891. var indices = this._renderingMesh.getIndices();
  20892. var extend;
  20893. //is this the only submesh?
  20894. if (this.indexStart === 0 && this.indexCount === indices.length) {
  20895. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  20896. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  20897. }
  20898. else {
  20899. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  20900. }
  20901. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20902. };
  20903. SubMesh.prototype._checkCollision = function (collider) {
  20904. return this.getBoundingInfo()._checkCollision(collider);
  20905. };
  20906. SubMesh.prototype.updateBoundingInfo = function (world) {
  20907. if (!this.getBoundingInfo()) {
  20908. this.refreshBoundingInfo();
  20909. }
  20910. this.getBoundingInfo().update(world);
  20911. };
  20912. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  20913. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  20914. };
  20915. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20916. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  20917. };
  20918. SubMesh.prototype.render = function (enableAlphaMode) {
  20919. this._renderingMesh.render(this, enableAlphaMode);
  20920. };
  20921. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  20922. if (!this._linesIndexBuffer) {
  20923. var linesIndices = [];
  20924. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20925. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  20926. }
  20927. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  20928. this.linesIndexCount = linesIndices.length;
  20929. }
  20930. return this._linesIndexBuffer;
  20931. };
  20932. SubMesh.prototype.canIntersects = function (ray) {
  20933. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  20934. };
  20935. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  20936. var intersectInfo = null;
  20937. // LineMesh first as it's also a Mesh...
  20938. if (this._mesh instanceof BABYLON.LinesMesh) {
  20939. var lineMesh = this._mesh;
  20940. // Line test
  20941. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  20942. var p0 = positions[indices[index]];
  20943. var p1 = positions[indices[index + 1]];
  20944. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  20945. if (length < 0) {
  20946. continue;
  20947. }
  20948. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  20949. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  20950. if (fastCheck) {
  20951. break;
  20952. }
  20953. }
  20954. }
  20955. }
  20956. else {
  20957. // Triangles test
  20958. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  20959. var p0 = positions[indices[index]];
  20960. var p1 = positions[indices[index + 1]];
  20961. var p2 = positions[indices[index + 2]];
  20962. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  20963. if (currentIntersectInfo) {
  20964. if (currentIntersectInfo.distance < 0) {
  20965. continue;
  20966. }
  20967. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20968. intersectInfo = currentIntersectInfo;
  20969. intersectInfo.faceId = index / 3;
  20970. if (fastCheck) {
  20971. break;
  20972. }
  20973. }
  20974. }
  20975. }
  20976. }
  20977. return intersectInfo;
  20978. };
  20979. // Clone
  20980. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  20981. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  20982. if (!this.IsGlobal) {
  20983. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  20984. }
  20985. return result;
  20986. };
  20987. // Dispose
  20988. SubMesh.prototype.dispose = function () {
  20989. if (this._linesIndexBuffer) {
  20990. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  20991. this._linesIndexBuffer = null;
  20992. }
  20993. // Remove from mesh
  20994. var index = this._mesh.subMeshes.indexOf(this);
  20995. this._mesh.subMeshes.splice(index, 1);
  20996. };
  20997. // Statics
  20998. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  20999. var minVertexIndex = Number.MAX_VALUE;
  21000. var maxVertexIndex = -Number.MAX_VALUE;
  21001. renderingMesh = renderingMesh || mesh;
  21002. var indices = renderingMesh.getIndices();
  21003. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21004. var vertexIndex = indices[index];
  21005. if (vertexIndex < minVertexIndex)
  21006. minVertexIndex = vertexIndex;
  21007. if (vertexIndex > maxVertexIndex)
  21008. maxVertexIndex = vertexIndex;
  21009. }
  21010. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21011. };
  21012. return SubMesh;
  21013. }());
  21014. BABYLON.SubMesh = SubMesh;
  21015. })(BABYLON || (BABYLON = {}));
  21016. var BABYLON;
  21017. (function (BABYLON) {
  21018. var MeshBuilder = (function () {
  21019. function MeshBuilder() {
  21020. }
  21021. /**
  21022. * Creates a box mesh.
  21023. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  21024. * The parameter `size` sets the size (float) of each box side (default 1).
  21025. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  21026. * 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).
  21027. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21028. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21029. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21030. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21031. */
  21032. MeshBuilder.CreateBox = function (name, options, scene) {
  21033. var box = new BABYLON.Mesh(name, scene);
  21034. var vertexData = BABYLON.VertexData.CreateBox(options);
  21035. vertexData.applyToMesh(box, options.updatable);
  21036. return box;
  21037. };
  21038. /**
  21039. * Creates a sphere mesh.
  21040. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  21041. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21042. * 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`).
  21043. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21044. * 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
  21045. * 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).
  21046. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21047. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21048. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21049. */
  21050. MeshBuilder.CreateSphere = function (name, options, scene) {
  21051. var sphere = new BABYLON.Mesh(name, scene);
  21052. var vertexData = BABYLON.VertexData.CreateSphere(options);
  21053. vertexData.applyToMesh(sphere, options.updatable);
  21054. return sphere;
  21055. };
  21056. /**
  21057. * Creates a plane polygonal mesh. By default, this is a disc.
  21058. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  21059. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21060. * 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.
  21061. * 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
  21062. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21063. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21064. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21065. */
  21066. MeshBuilder.CreateDisc = function (name, options, scene) {
  21067. var disc = new BABYLON.Mesh(name, scene);
  21068. var vertexData = BABYLON.VertexData.CreateDisc(options);
  21069. vertexData.applyToMesh(disc, options.updatable);
  21070. return disc;
  21071. };
  21072. /**
  21073. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21074. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  21075. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21076. * 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`).
  21077. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21078. * 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.
  21079. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21080. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21082. */
  21083. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  21084. var sphere = new BABYLON.Mesh(name, scene);
  21085. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  21086. vertexData.applyToMesh(sphere, options.updatable);
  21087. return sphere;
  21088. };
  21089. ;
  21090. /**
  21091. * Creates a ribbon mesh.
  21092. * 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.
  21093. *
  21094. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21095. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21096. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21097. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21098. * 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.
  21099. * 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.
  21100. * 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
  21101. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21102. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21103. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21105. */
  21106. MeshBuilder.CreateRibbon = function (name, options, scene) {
  21107. var pathArray = options.pathArray;
  21108. var closeArray = options.closeArray;
  21109. var closePath = options.closePath;
  21110. var offset = options.offset;
  21111. var sideOrientation = options.sideOrientation;
  21112. var instance = options.instance;
  21113. var updatable = options.updatable;
  21114. if (instance) {
  21115. // positionFunction : ribbon case
  21116. // only pathArray and sideOrientation parameters are taken into account for positions update
  21117. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  21118. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  21119. var positionFunction = function (positions) {
  21120. var minlg = pathArray[0].length;
  21121. var i = 0;
  21122. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21123. for (var si = 1; si <= ns; si++) {
  21124. for (var p = 0; p < pathArray.length; p++) {
  21125. var path = pathArray[p];
  21126. var l = path.length;
  21127. minlg = (minlg < l) ? minlg : l;
  21128. var j = 0;
  21129. while (j < minlg) {
  21130. positions[i] = path[j].x;
  21131. positions[i + 1] = path[j].y;
  21132. positions[i + 2] = path[j].z;
  21133. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21134. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21135. }
  21136. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21137. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21138. }
  21139. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21140. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21141. }
  21142. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21143. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21144. }
  21145. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21146. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21147. }
  21148. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21149. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21150. }
  21151. j++;
  21152. i += 3;
  21153. }
  21154. if (instance._closePath) {
  21155. positions[i] = path[0].x;
  21156. positions[i + 1] = path[0].y;
  21157. positions[i + 2] = path[0].z;
  21158. i += 3;
  21159. }
  21160. }
  21161. }
  21162. };
  21163. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21164. positionFunction(positions);
  21165. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21166. instance._boundingInfo.update(instance._worldMatrix);
  21167. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21168. if (!(instance.areNormalsFrozen)) {
  21169. var indices = instance.getIndices();
  21170. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21171. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21172. if (instance._closePath) {
  21173. var indexFirst = 0;
  21174. var indexLast = 0;
  21175. for (var p = 0; p < pathArray.length; p++) {
  21176. indexFirst = instance._idx[p] * 3;
  21177. if (p + 1 < pathArray.length) {
  21178. indexLast = (instance._idx[p + 1] - 1) * 3;
  21179. }
  21180. else {
  21181. indexLast = normals.length - 3;
  21182. }
  21183. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21184. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21185. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21186. normals[indexLast] = normals[indexFirst];
  21187. normals[indexLast + 1] = normals[indexFirst + 1];
  21188. normals[indexLast + 2] = normals[indexFirst + 2];
  21189. }
  21190. }
  21191. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21192. }
  21193. return instance;
  21194. }
  21195. else {
  21196. var ribbon = new BABYLON.Mesh(name, scene);
  21197. ribbon.sideOrientation = sideOrientation;
  21198. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21199. if (closePath) {
  21200. ribbon._idx = vertexData._idx;
  21201. }
  21202. ribbon._closePath = closePath;
  21203. ribbon._closeArray = closeArray;
  21204. vertexData.applyToMesh(ribbon, updatable);
  21205. return ribbon;
  21206. }
  21207. };
  21208. /**
  21209. * Creates a cylinder or a cone mesh.
  21210. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21211. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21212. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21213. * 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.
  21214. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21215. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21216. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21217. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21218. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21219. * 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).
  21220. * 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
  21221. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21222. * 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
  21223. * 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.
  21224. * If `enclose` is false, a ring surface is one element.
  21225. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21226. * 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
  21227. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21228. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21229. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21230. */
  21231. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21232. var cylinder = new BABYLON.Mesh(name, scene);
  21233. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21234. vertexData.applyToMesh(cylinder, options.updatable);
  21235. return cylinder;
  21236. };
  21237. /**
  21238. * Creates a torus mesh.
  21239. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21240. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21241. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21242. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21243. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21244. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21245. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21246. */
  21247. MeshBuilder.CreateTorus = function (name, options, scene) {
  21248. var torus = new BABYLON.Mesh(name, scene);
  21249. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21250. vertexData.applyToMesh(torus, options.updatable);
  21251. return torus;
  21252. };
  21253. /**
  21254. * Creates a torus knot mesh.
  21255. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21256. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21257. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21258. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21259. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21260. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21261. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21262. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21263. */
  21264. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21265. var torusKnot = new BABYLON.Mesh(name, scene);
  21266. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21267. vertexData.applyToMesh(torusKnot, options.updatable);
  21268. return torusKnot;
  21269. };
  21270. /**
  21271. * Creates a line system mesh.
  21272. * A line system is a pool of many lines gathered in a single mesh.
  21273. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  21274. * 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.
  21275. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  21276. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  21277. * 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
  21278. * 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
  21279. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  21280. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21281. */
  21282. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  21283. var instance = options.instance;
  21284. var lines = options.lines;
  21285. if (instance) {
  21286. var positionFunction = function (positions) {
  21287. var i = 0;
  21288. for (var l = 0; l < lines.length; l++) {
  21289. var points = lines[l];
  21290. for (var p = 0; p < points.length; p++) {
  21291. positions[i] = points[p].x;
  21292. positions[i + 1] = points[p].y;
  21293. positions[i + 2] = points[p].z;
  21294. i += 3;
  21295. }
  21296. }
  21297. };
  21298. instance.updateMeshPositions(positionFunction, false);
  21299. return instance;
  21300. }
  21301. // line system creation
  21302. var lineSystem = new BABYLON.LinesMesh(name, scene);
  21303. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  21304. vertexData.applyToMesh(lineSystem, options.updatable);
  21305. return lineSystem;
  21306. };
  21307. /**
  21308. * Creates a line mesh.
  21309. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  21310. * 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.
  21311. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21312. * The parameter `points` is an array successive Vector3.
  21313. * 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
  21314. * When updating an instance, remember that only point positions can change, not the number of points.
  21315. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21316. */
  21317. MeshBuilder.CreateLines = function (name, options, scene) {
  21318. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  21319. return lines;
  21320. };
  21321. /**
  21322. * Creates a dashed line mesh.
  21323. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  21324. * 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.
  21325. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21326. * The parameter `points` is an array successive Vector3.
  21327. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21328. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21329. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21330. * 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
  21331. * When updating an instance, remember that only point positions can change, not the number of points.
  21332. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21333. */
  21334. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  21335. var points = options.points;
  21336. var instance = options.instance;
  21337. var gapSize = options.gapSize;
  21338. var dashNb = options.dashNb;
  21339. var dashSize = options.dashSize;
  21340. if (instance) {
  21341. var positionFunction = function (positions) {
  21342. var curvect = BABYLON.Vector3.Zero();
  21343. var nbSeg = positions.length / 6;
  21344. var lg = 0;
  21345. var nb = 0;
  21346. var shft = 0;
  21347. var dashshft = 0;
  21348. var curshft = 0;
  21349. var p = 0;
  21350. var i = 0;
  21351. var j = 0;
  21352. for (i = 0; i < points.length - 1; i++) {
  21353. points[i + 1].subtractToRef(points[i], curvect);
  21354. lg += curvect.length();
  21355. }
  21356. shft = lg / nbSeg;
  21357. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  21358. for (i = 0; i < points.length - 1; i++) {
  21359. points[i + 1].subtractToRef(points[i], curvect);
  21360. nb = Math.floor(curvect.length() / shft);
  21361. curvect.normalize();
  21362. j = 0;
  21363. while (j < nb && p < positions.length) {
  21364. curshft = shft * j;
  21365. positions[p] = points[i].x + curshft * curvect.x;
  21366. positions[p + 1] = points[i].y + curshft * curvect.y;
  21367. positions[p + 2] = points[i].z + curshft * curvect.z;
  21368. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  21369. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  21370. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  21371. p += 6;
  21372. j++;
  21373. }
  21374. }
  21375. while (p < positions.length) {
  21376. positions[p] = points[i].x;
  21377. positions[p + 1] = points[i].y;
  21378. positions[p + 2] = points[i].z;
  21379. p += 3;
  21380. }
  21381. };
  21382. instance.updateMeshPositions(positionFunction, false);
  21383. return instance;
  21384. }
  21385. // dashed lines creation
  21386. var dashedLines = new BABYLON.LinesMesh(name, scene);
  21387. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  21388. vertexData.applyToMesh(dashedLines, options.updatable);
  21389. dashedLines.dashSize = dashSize;
  21390. dashedLines.gapSize = gapSize;
  21391. return dashedLines;
  21392. };
  21393. /**
  21394. * Creates an extruded shape mesh.
  21395. * 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.
  21396. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  21397. *
  21398. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21399. * 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
  21400. * extruded along the Z axis.
  21401. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21402. * 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.
  21403. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21404. * 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
  21405. * 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
  21406. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21407. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21408. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21409. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21410. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21411. */
  21412. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  21413. var path = options.path;
  21414. var shape = options.shape;
  21415. var scale = options.scale || 1;
  21416. var rotation = options.rotation || 0;
  21417. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21418. var updatable = options.updatable;
  21419. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21420. var instance = options.instance;
  21421. var invertUV = options.invertUV || false;
  21422. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  21423. };
  21424. /**
  21425. * Creates an custom extruded shape mesh.
  21426. * 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.
  21427. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  21428. *
  21429. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21430. * 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
  21431. * extruded along the Z axis.
  21432. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21433. * 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
  21434. * and the distance of this point from the begining of the path :
  21435. * ```javascript
  21436. * var rotationFunction = function(i, distance) {
  21437. * // do things
  21438. * return rotationValue; }
  21439. * ```
  21440. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21441. * 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
  21442. * and the distance of this point from the begining of the path :
  21443. * ```javascript
  21444. * var scaleFunction = function(i, distance) {
  21445. * // do things
  21446. * return scaleValue;}
  21447. * ```
  21448. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21449. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21450. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21451. * 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
  21452. * 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
  21453. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21454. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21455. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21456. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21457. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21458. */
  21459. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  21460. var path = options.path;
  21461. var shape = options.shape;
  21462. var scaleFunction = options.scaleFunction || (function () { return 1; });
  21463. var rotationFunction = options.rotationFunction || (function () { return 0; });
  21464. var ribbonCloseArray = options.ribbonCloseArray || false;
  21465. var ribbonClosePath = options.ribbonClosePath || false;
  21466. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  21467. var updatable = options.updatable;
  21468. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21469. var instance = options.instance;
  21470. var invertUV = options.invertUV || false;
  21471. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  21472. };
  21473. /**
  21474. * Creates lathe mesh.
  21475. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21476. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  21477. *
  21478. * 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
  21479. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21480. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21481. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21482. * 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.
  21483. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  21484. * 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
  21485. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21486. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21487. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21489. */
  21490. MeshBuilder.CreateLathe = function (name, options, scene) {
  21491. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  21492. var closed = (options.closed === undefined) ? true : options.closed;
  21493. var shape = options.shape;
  21494. var radius = options.radius || 1;
  21495. var tessellation = options.tessellation || 64;
  21496. var updatable = options.updatable;
  21497. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21498. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21499. var pi2 = Math.PI * 2;
  21500. var paths = new Array();
  21501. var invertUV = options.invertUV || false;
  21502. var i = 0;
  21503. var p = 0;
  21504. var step = pi2 / tessellation * arc;
  21505. var rotated;
  21506. var path = new Array();
  21507. ;
  21508. for (i = 0; i <= tessellation; i++) {
  21509. var path = [];
  21510. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  21511. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  21512. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  21513. }
  21514. for (p = 0; p < shape.length; p++) {
  21515. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  21516. path.push(rotated);
  21517. }
  21518. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  21519. 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));
  21520. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  21521. }
  21522. paths.push(path);
  21523. }
  21524. // lathe ribbon
  21525. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  21526. return lathe;
  21527. };
  21528. /**
  21529. * Creates a plane mesh.
  21530. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21531. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21532. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  21533. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  21534. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21535. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21537. */
  21538. MeshBuilder.CreatePlane = function (name, options, scene) {
  21539. var plane = new BABYLON.Mesh(name, scene);
  21540. var vertexData = BABYLON.VertexData.CreatePlane(options);
  21541. vertexData.applyToMesh(plane, options.updatable);
  21542. if (options.sourcePlane) {
  21543. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  21544. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  21545. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  21546. plane.rotate(vectorProduct, product);
  21547. }
  21548. return plane;
  21549. };
  21550. /**
  21551. * Creates a ground mesh.
  21552. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  21553. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21554. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21555. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21556. */
  21557. MeshBuilder.CreateGround = function (name, options, scene) {
  21558. var ground = new BABYLON.GroundMesh(name, scene);
  21559. ground._setReady(false);
  21560. ground._subdivisions = options.subdivisions || 1;
  21561. ground._width = options.width || 1;
  21562. ground._height = options.height || 1;
  21563. ground._maxX = ground._width / 2;
  21564. ground._maxZ = ground._height / 2;
  21565. ground._minX = -ground._maxX;
  21566. ground._minZ = -ground._maxZ;
  21567. var vertexData = BABYLON.VertexData.CreateGround(options);
  21568. vertexData.applyToMesh(ground, options.updatable);
  21569. ground._setReady(true);
  21570. return ground;
  21571. };
  21572. /**
  21573. * Creates a tiled ground mesh.
  21574. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  21575. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21576. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21577. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21578. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21579. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21580. * numbers of subdivisions on the ground width and height of each tile.
  21581. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21582. */
  21583. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  21584. var tiledGround = new BABYLON.Mesh(name, scene);
  21585. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  21586. vertexData.applyToMesh(tiledGround, options.updatable);
  21587. return tiledGround;
  21588. };
  21589. /**
  21590. * Creates a ground mesh from a height map.
  21591. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21592. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  21593. * The parameter `url` sets the URL of the height map image resource.
  21594. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21595. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21596. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21597. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21598. * 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).
  21599. * This function is passed the newly built mesh :
  21600. * ```javascript
  21601. * function(mesh) { // do things
  21602. * return; }
  21603. * ```
  21604. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21605. */
  21606. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  21607. var width = options.width || 10.0;
  21608. var height = options.height || 10.0;
  21609. var subdivisions = options.subdivisions || 1 | 0;
  21610. var minHeight = options.minHeight || 0.0;
  21611. var maxHeight = options.maxHeight || 10.0;
  21612. var updatable = options.updatable;
  21613. var onReady = options.onReady;
  21614. var ground = new BABYLON.GroundMesh(name, scene);
  21615. ground._subdivisions = subdivisions;
  21616. ground._width = width;
  21617. ground._height = height;
  21618. ground._maxX = ground._width / 2.0;
  21619. ground._maxZ = ground._height / 2.0;
  21620. ground._minX = -ground._maxX;
  21621. ground._minZ = -ground._maxZ;
  21622. ground._setReady(false);
  21623. var onload = function (img) {
  21624. // Getting height map data
  21625. var canvas = document.createElement("canvas");
  21626. var context = canvas.getContext("2d");
  21627. var bufferWidth = img.width;
  21628. var bufferHeight = img.height;
  21629. canvas.width = bufferWidth;
  21630. canvas.height = bufferHeight;
  21631. context.drawImage(img, 0, 0);
  21632. // Create VertexData from map data
  21633. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21634. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  21635. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  21636. width: width, height: height,
  21637. subdivisions: subdivisions,
  21638. minHeight: minHeight, maxHeight: maxHeight,
  21639. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  21640. });
  21641. vertexData.applyToMesh(ground, updatable);
  21642. ground._setReady(true);
  21643. //execute ready callback, if set
  21644. if (onReady) {
  21645. onReady(ground);
  21646. }
  21647. };
  21648. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21649. return ground;
  21650. };
  21651. /**
  21652. * Creates a tube mesh.
  21653. * 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.
  21654. *
  21655. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  21656. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21657. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21658. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21659. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21660. * 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.
  21661. * It must return a radius value (positive float) :
  21662. * ```javascript
  21663. * var radiusFunction = function(i, distance) {
  21664. * // do things
  21665. * return radius; }
  21666. * ```
  21667. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  21668. * 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
  21669. * 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
  21670. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21671. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21672. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21673. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21674. */
  21675. MeshBuilder.CreateTube = function (name, options, scene) {
  21676. var path = options.path;
  21677. var radius = options.radius || 1.0;
  21678. var tessellation = options.tessellation || 64 | 0;
  21679. var radiusFunction = options.radiusFunction;
  21680. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  21681. var invertUV = options.invertUV || false;
  21682. var updatable = options.updatable;
  21683. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21684. var instance = options.instance;
  21685. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  21686. // tube geometry
  21687. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  21688. var tangents = path3D.getTangents();
  21689. var normals = path3D.getNormals();
  21690. var distances = path3D.getDistances();
  21691. var pi2 = Math.PI * 2;
  21692. var step = pi2 / tessellation * arc;
  21693. var returnRadius = function () { return radius; };
  21694. var radiusFunctionFinal = radiusFunction || returnRadius;
  21695. var circlePath;
  21696. var rad;
  21697. var normal;
  21698. var rotated;
  21699. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21700. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21701. for (var i = 0; i < path.length; i++) {
  21702. rad = radiusFunctionFinal(i, distances[i]); // current radius
  21703. circlePath = Array(); // current circle array
  21704. normal = normals[i]; // current normal
  21705. for (var t = 0; t < tessellation; t++) {
  21706. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  21707. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  21708. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  21709. rotated.scaleInPlace(rad).addInPlace(path[i]);
  21710. circlePath[t] = rotated;
  21711. }
  21712. circlePaths[index] = circlePath;
  21713. index++;
  21714. }
  21715. // cap
  21716. var capPath = function (nbPoints, pathIndex) {
  21717. var pointCap = Array();
  21718. for (var i = 0; i < nbPoints; i++) {
  21719. pointCap.push(path[pathIndex]);
  21720. }
  21721. return pointCap;
  21722. };
  21723. switch (cap) {
  21724. case BABYLON.Mesh.NO_CAP:
  21725. break;
  21726. case BABYLON.Mesh.CAP_START:
  21727. circlePaths[0] = capPath(tessellation, 0);
  21728. circlePaths[1] = circlePaths[2].slice(0);
  21729. break;
  21730. case BABYLON.Mesh.CAP_END:
  21731. circlePaths[index] = circlePaths[index - 1].slice(0);
  21732. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21733. break;
  21734. case BABYLON.Mesh.CAP_ALL:
  21735. circlePaths[0] = capPath(tessellation, 0);
  21736. circlePaths[1] = circlePaths[2].slice(0);
  21737. circlePaths[index] = circlePaths[index - 1].slice(0);
  21738. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  21739. break;
  21740. default:
  21741. break;
  21742. }
  21743. return circlePaths;
  21744. };
  21745. var path3D;
  21746. var pathArray;
  21747. if (instance) {
  21748. var arc = options.arc || instance.arc;
  21749. path3D = (instance.path3D).update(path);
  21750. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  21751. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  21752. instance.path3D = path3D;
  21753. instance.pathArray = pathArray;
  21754. instance.arc = arc;
  21755. return instance;
  21756. }
  21757. // tube creation
  21758. path3D = new BABYLON.Path3D(path);
  21759. var newPathArray = new Array();
  21760. cap = (cap < 0 || cap > 3) ? 0 : cap;
  21761. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  21762. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  21763. tube.pathArray = pathArray;
  21764. tube.path3D = path3D;
  21765. tube.tessellation = tessellation;
  21766. tube.cap = cap;
  21767. tube.arc = options.arc;
  21768. return tube;
  21769. };
  21770. /**
  21771. * Creates a polyhedron mesh.
  21772. *
  21773. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  21774. * 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
  21775. * to choose the wanted type.
  21776. * The parameter `size` (positive float, default 1) sets the polygon size.
  21777. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21778. * 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`.
  21779. * 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
  21780. * 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)`).
  21781. * 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
  21782. * 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.
  21783. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21784. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21785. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21786. */
  21787. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  21788. var polyhedron = new BABYLON.Mesh(name, scene);
  21789. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  21790. vertexData.applyToMesh(polyhedron, options.updatable);
  21791. return polyhedron;
  21792. };
  21793. /**
  21794. * Creates a decal mesh.
  21795. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  21796. * 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.
  21797. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21798. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21799. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21800. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21801. */
  21802. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  21803. var indices = sourceMesh.getIndices();
  21804. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21805. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21806. var position = options.position || BABYLON.Vector3.Zero();
  21807. var normal = options.normal || BABYLON.Vector3.Up();
  21808. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  21809. var angle = options.angle || 0;
  21810. // Getting correct rotation
  21811. if (!normal) {
  21812. var target = new BABYLON.Vector3(0, 0, 1);
  21813. var camera = sourceMesh.getScene().activeCamera;
  21814. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  21815. normal = camera.globalPosition.subtract(cameraWorldTarget);
  21816. }
  21817. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  21818. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  21819. var pitch = Math.atan2(normal.y, len);
  21820. // Matrix
  21821. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  21822. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  21823. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  21824. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  21825. var vertexData = new BABYLON.VertexData();
  21826. vertexData.indices = [];
  21827. vertexData.positions = [];
  21828. vertexData.normals = [];
  21829. vertexData.uvs = [];
  21830. var currentVertexDataIndex = 0;
  21831. var extractDecalVector3 = function (indexId) {
  21832. var vertexId = indices[indexId];
  21833. var result = new BABYLON.PositionNormalVertex();
  21834. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  21835. // Send vector to decal local world
  21836. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  21837. // Get normal
  21838. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  21839. return result;
  21840. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  21841. var clip = function (vertices, axis) {
  21842. if (vertices.length === 0) {
  21843. return vertices;
  21844. }
  21845. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  21846. var clipVertices = function (v0, v1) {
  21847. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  21848. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  21849. };
  21850. var result = new Array();
  21851. for (var index = 0; index < vertices.length; index += 3) {
  21852. var v1Out;
  21853. var v2Out;
  21854. var v3Out;
  21855. var total = 0;
  21856. var nV1, nV2, nV3, nV4;
  21857. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  21858. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  21859. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  21860. v1Out = d1 > 0;
  21861. v2Out = d2 > 0;
  21862. v3Out = d3 > 0;
  21863. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  21864. switch (total) {
  21865. case 0:
  21866. result.push(vertices[index]);
  21867. result.push(vertices[index + 1]);
  21868. result.push(vertices[index + 2]);
  21869. break;
  21870. case 1:
  21871. if (v1Out) {
  21872. nV1 = vertices[index + 1];
  21873. nV2 = vertices[index + 2];
  21874. nV3 = clipVertices(vertices[index], nV1);
  21875. nV4 = clipVertices(vertices[index], nV2);
  21876. }
  21877. if (v2Out) {
  21878. nV1 = vertices[index];
  21879. nV2 = vertices[index + 2];
  21880. nV3 = clipVertices(vertices[index + 1], nV1);
  21881. nV4 = clipVertices(vertices[index + 1], nV2);
  21882. result.push(nV3);
  21883. result.push(nV2.clone());
  21884. result.push(nV1.clone());
  21885. result.push(nV2.clone());
  21886. result.push(nV3.clone());
  21887. result.push(nV4);
  21888. break;
  21889. }
  21890. if (v3Out) {
  21891. nV1 = vertices[index];
  21892. nV2 = vertices[index + 1];
  21893. nV3 = clipVertices(vertices[index + 2], nV1);
  21894. nV4 = clipVertices(vertices[index + 2], nV2);
  21895. }
  21896. result.push(nV1.clone());
  21897. result.push(nV2.clone());
  21898. result.push(nV3);
  21899. result.push(nV4);
  21900. result.push(nV3.clone());
  21901. result.push(nV2.clone());
  21902. break;
  21903. case 2:
  21904. if (!v1Out) {
  21905. nV1 = vertices[index].clone();
  21906. nV2 = clipVertices(nV1, vertices[index + 1]);
  21907. nV3 = clipVertices(nV1, vertices[index + 2]);
  21908. result.push(nV1);
  21909. result.push(nV2);
  21910. result.push(nV3);
  21911. }
  21912. if (!v2Out) {
  21913. nV1 = vertices[index + 1].clone();
  21914. nV2 = clipVertices(nV1, vertices[index + 2]);
  21915. nV3 = clipVertices(nV1, vertices[index]);
  21916. result.push(nV1);
  21917. result.push(nV2);
  21918. result.push(nV3);
  21919. }
  21920. if (!v3Out) {
  21921. nV1 = vertices[index + 2].clone();
  21922. nV2 = clipVertices(nV1, vertices[index]);
  21923. nV3 = clipVertices(nV1, vertices[index + 1]);
  21924. result.push(nV1);
  21925. result.push(nV2);
  21926. result.push(nV3);
  21927. }
  21928. break;
  21929. case 3:
  21930. break;
  21931. }
  21932. }
  21933. return result;
  21934. };
  21935. for (var index = 0; index < indices.length; index += 3) {
  21936. var faceVertices = new Array();
  21937. faceVertices.push(extractDecalVector3(index));
  21938. faceVertices.push(extractDecalVector3(index + 1));
  21939. faceVertices.push(extractDecalVector3(index + 2));
  21940. // Clip
  21941. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  21942. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  21943. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  21944. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  21945. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  21946. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  21947. if (faceVertices.length === 0) {
  21948. continue;
  21949. }
  21950. // Add UVs and get back to world
  21951. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  21952. var vertex = faceVertices[vIndex];
  21953. //TODO check for Int32Array
  21954. vertexData.indices.push(currentVertexDataIndex);
  21955. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  21956. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  21957. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  21958. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  21959. currentVertexDataIndex++;
  21960. }
  21961. }
  21962. // Return mesh
  21963. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  21964. vertexData.applyToMesh(decal);
  21965. decal.position = position.clone();
  21966. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  21967. return decal;
  21968. };
  21969. // Privates
  21970. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  21971. // extrusion geometry
  21972. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  21973. var tangents = path3D.getTangents();
  21974. var normals = path3D.getNormals();
  21975. var binormals = path3D.getBinormals();
  21976. var distances = path3D.getDistances();
  21977. var angle = 0;
  21978. var returnScale = function () { return scale; };
  21979. var returnRotation = function () { return rotation; };
  21980. var rotate = custom ? rotateFunction : returnRotation;
  21981. var scl = custom ? scaleFunction : returnScale;
  21982. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  21983. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  21984. for (var i = 0; i < curve.length; i++) {
  21985. var shapePath = new Array();
  21986. var angleStep = rotate(i, distances[i]);
  21987. var scaleRatio = scl(i, distances[i]);
  21988. for (var p = 0; p < shape.length; p++) {
  21989. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  21990. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  21991. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  21992. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  21993. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  21994. shapePath[p] = rotated;
  21995. }
  21996. shapePaths[index] = shapePath;
  21997. angle += angleStep;
  21998. index++;
  21999. }
  22000. // cap
  22001. var capPath = function (shapePath) {
  22002. var pointCap = Array();
  22003. var barycenter = BABYLON.Vector3.Zero();
  22004. var i;
  22005. for (i = 0; i < shapePath.length; i++) {
  22006. barycenter.addInPlace(shapePath[i]);
  22007. }
  22008. barycenter.scaleInPlace(1 / shapePath.length);
  22009. for (i = 0; i < shapePath.length; i++) {
  22010. pointCap.push(barycenter);
  22011. }
  22012. return pointCap;
  22013. };
  22014. switch (cap) {
  22015. case BABYLON.Mesh.NO_CAP:
  22016. break;
  22017. case BABYLON.Mesh.CAP_START:
  22018. shapePaths[0] = capPath(shapePaths[2]);
  22019. shapePaths[1] = shapePaths[2].slice(0);
  22020. break;
  22021. case BABYLON.Mesh.CAP_END:
  22022. shapePaths[index] = shapePaths[index - 1];
  22023. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22024. break;
  22025. case BABYLON.Mesh.CAP_ALL:
  22026. shapePaths[0] = capPath(shapePaths[2]);
  22027. shapePaths[1] = shapePaths[2].slice(0);
  22028. shapePaths[index] = shapePaths[index - 1];
  22029. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22030. break;
  22031. default:
  22032. break;
  22033. }
  22034. return shapePaths;
  22035. };
  22036. var path3D;
  22037. var pathArray;
  22038. if (instance) {
  22039. path3D = (instance.path3D).update(curve);
  22040. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  22041. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  22042. return instance;
  22043. }
  22044. // extruded shape creation
  22045. path3D = new BABYLON.Path3D(curve);
  22046. var newShapePaths = new Array();
  22047. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22048. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  22049. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  22050. extrudedGeneric.pathArray = pathArray;
  22051. extrudedGeneric.path3D = path3D;
  22052. extrudedGeneric.cap = cap;
  22053. return extrudedGeneric;
  22054. };
  22055. return MeshBuilder;
  22056. }());
  22057. BABYLON.MeshBuilder = MeshBuilder;
  22058. })(BABYLON || (BABYLON = {}));
  22059. var BABYLON;
  22060. (function (BABYLON) {
  22061. var BaseTexture = (function () {
  22062. function BaseTexture(scene) {
  22063. this.hasAlpha = false;
  22064. this.getAlphaFromRGB = false;
  22065. this.level = 1;
  22066. this.coordinatesIndex = 0;
  22067. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22068. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22069. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22070. this.anisotropicFilteringLevel = 4;
  22071. this.isCube = false;
  22072. this.isRenderTarget = false;
  22073. this.animations = new Array();
  22074. /**
  22075. * An event triggered when the texture is disposed.
  22076. * @type {BABYLON.Observable}
  22077. */
  22078. this.onDisposeObservable = new BABYLON.Observable();
  22079. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22080. this._scene = scene;
  22081. this._scene.textures.push(this);
  22082. }
  22083. BaseTexture.prototype.toString = function () {
  22084. return this.name;
  22085. };
  22086. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22087. set: function (callback) {
  22088. if (this._onDisposeObserver) {
  22089. this.onDisposeObservable.remove(this._onDisposeObserver);
  22090. }
  22091. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22092. },
  22093. enumerable: true,
  22094. configurable: true
  22095. });
  22096. BaseTexture.prototype.getScene = function () {
  22097. return this._scene;
  22098. };
  22099. BaseTexture.prototype.getTextureMatrix = function () {
  22100. return null;
  22101. };
  22102. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22103. return null;
  22104. };
  22105. BaseTexture.prototype.getInternalTexture = function () {
  22106. return this._texture;
  22107. };
  22108. BaseTexture.prototype.isReady = function () {
  22109. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22110. return true;
  22111. }
  22112. if (this._texture) {
  22113. return this._texture.isReady;
  22114. }
  22115. return false;
  22116. };
  22117. BaseTexture.prototype.getSize = function () {
  22118. if (this._texture._width) {
  22119. return new BABYLON.Size(this._texture._width, this._texture._height);
  22120. }
  22121. if (this._texture._size) {
  22122. return new BABYLON.Size(this._texture._size, this._texture._size);
  22123. }
  22124. return BABYLON.Size.Zero();
  22125. };
  22126. BaseTexture.prototype.getBaseSize = function () {
  22127. if (!this.isReady() || !this._texture)
  22128. return BABYLON.Size.Zero();
  22129. if (this._texture._size) {
  22130. return new BABYLON.Size(this._texture._size, this._texture._size);
  22131. }
  22132. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22133. };
  22134. BaseTexture.prototype.scale = function (ratio) {
  22135. };
  22136. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22137. get: function () {
  22138. return false;
  22139. },
  22140. enumerable: true,
  22141. configurable: true
  22142. });
  22143. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22144. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22145. for (var index = 0; index < texturesCache.length; index++) {
  22146. var texturesCacheEntry = texturesCache[index];
  22147. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22148. texturesCache.splice(index, 1);
  22149. return;
  22150. }
  22151. }
  22152. };
  22153. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22154. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22155. for (var index = 0; index < texturesCache.length; index++) {
  22156. var texturesCacheEntry = texturesCache[index];
  22157. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22158. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22159. texturesCacheEntry.references++;
  22160. return texturesCacheEntry;
  22161. }
  22162. }
  22163. }
  22164. return null;
  22165. };
  22166. BaseTexture.prototype.delayLoad = function () {
  22167. };
  22168. BaseTexture.prototype.clone = function () {
  22169. return null;
  22170. };
  22171. BaseTexture.prototype.releaseInternalTexture = function () {
  22172. if (this._texture) {
  22173. this._scene.getEngine().releaseInternalTexture(this._texture);
  22174. delete this._texture;
  22175. }
  22176. };
  22177. BaseTexture.prototype.dispose = function () {
  22178. // Animations
  22179. this.getScene().stopAnimation(this);
  22180. // Remove from scene
  22181. var index = this._scene.textures.indexOf(this);
  22182. if (index >= 0) {
  22183. this._scene.textures.splice(index, 1);
  22184. }
  22185. if (this._texture === undefined) {
  22186. return;
  22187. }
  22188. // Release
  22189. this.releaseInternalTexture();
  22190. // Callback
  22191. this.onDisposeObservable.notifyObservers(this);
  22192. this.onDisposeObservable.clear();
  22193. };
  22194. BaseTexture.prototype.serialize = function () {
  22195. if (!this.name) {
  22196. return null;
  22197. }
  22198. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22199. // Animations
  22200. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22201. return serializationObject;
  22202. };
  22203. __decorate([
  22204. BABYLON.serialize()
  22205. ], BaseTexture.prototype, "name", void 0);
  22206. __decorate([
  22207. BABYLON.serialize()
  22208. ], BaseTexture.prototype, "hasAlpha", void 0);
  22209. __decorate([
  22210. BABYLON.serialize()
  22211. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22212. __decorate([
  22213. BABYLON.serialize()
  22214. ], BaseTexture.prototype, "level", void 0);
  22215. __decorate([
  22216. BABYLON.serialize()
  22217. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22218. __decorate([
  22219. BABYLON.serialize()
  22220. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22221. __decorate([
  22222. BABYLON.serialize()
  22223. ], BaseTexture.prototype, "wrapU", void 0);
  22224. __decorate([
  22225. BABYLON.serialize()
  22226. ], BaseTexture.prototype, "wrapV", void 0);
  22227. __decorate([
  22228. BABYLON.serialize()
  22229. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22230. __decorate([
  22231. BABYLON.serialize()
  22232. ], BaseTexture.prototype, "isCube", void 0);
  22233. __decorate([
  22234. BABYLON.serialize()
  22235. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22236. return BaseTexture;
  22237. }());
  22238. BABYLON.BaseTexture = BaseTexture;
  22239. })(BABYLON || (BABYLON = {}));
  22240. var BABYLON;
  22241. (function (BABYLON) {
  22242. var Texture = (function (_super) {
  22243. __extends(Texture, _super);
  22244. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22245. var _this = this;
  22246. if (noMipmap === void 0) { noMipmap = false; }
  22247. if (invertY === void 0) { invertY = true; }
  22248. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22249. if (onLoad === void 0) { onLoad = null; }
  22250. if (onError === void 0) { onError = null; }
  22251. if (buffer === void 0) { buffer = null; }
  22252. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22253. _super.call(this, scene);
  22254. this.uOffset = 0;
  22255. this.vOffset = 0;
  22256. this.uScale = 1.0;
  22257. this.vScale = 1.0;
  22258. this.uAng = 0;
  22259. this.vAng = 0;
  22260. this.wAng = 0;
  22261. this.name = url;
  22262. this.url = url;
  22263. this._noMipmap = noMipmap;
  22264. this._invertY = invertY;
  22265. this._samplingMode = samplingMode;
  22266. this._buffer = buffer;
  22267. this._deleteBuffer = deleteBuffer;
  22268. if (!url) {
  22269. return;
  22270. }
  22271. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  22272. var load = function () {
  22273. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  22274. _this.onLoadObservable.notifyObservers(true);
  22275. }
  22276. if (onLoad) {
  22277. onLoad();
  22278. }
  22279. };
  22280. if (!this._texture) {
  22281. if (!scene.useDelayedTextureLoading) {
  22282. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  22283. if (deleteBuffer) {
  22284. delete this._buffer;
  22285. }
  22286. }
  22287. else {
  22288. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22289. this._delayedOnLoad = load;
  22290. this._delayedOnError = onError;
  22291. }
  22292. }
  22293. else {
  22294. if (this._texture.isReady) {
  22295. BABYLON.Tools.SetImmediate(function () { return load(); });
  22296. }
  22297. else {
  22298. this._texture.onLoadedCallbacks.push(load);
  22299. }
  22300. }
  22301. }
  22302. Object.defineProperty(Texture.prototype, "noMipmap", {
  22303. get: function () {
  22304. return this._noMipmap;
  22305. },
  22306. enumerable: true,
  22307. configurable: true
  22308. });
  22309. Texture.prototype.delayLoad = function () {
  22310. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22311. return;
  22312. }
  22313. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22314. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  22315. if (!this._texture) {
  22316. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  22317. if (this._deleteBuffer) {
  22318. delete this._buffer;
  22319. }
  22320. }
  22321. };
  22322. Texture.prototype.updateSamplingMode = function (samplingMode) {
  22323. if (!this._texture) {
  22324. return;
  22325. }
  22326. this._samplingMode = samplingMode;
  22327. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  22328. };
  22329. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  22330. x *= this.uScale;
  22331. y *= this.vScale;
  22332. x -= 0.5 * this.uScale;
  22333. y -= 0.5 * this.vScale;
  22334. z -= 0.5;
  22335. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  22336. t.x += 0.5 * this.uScale + this.uOffset;
  22337. t.y += 0.5 * this.vScale + this.vOffset;
  22338. t.z += 0.5;
  22339. };
  22340. Texture.prototype.getTextureMatrix = function () {
  22341. if (this.uOffset === this._cachedUOffset &&
  22342. this.vOffset === this._cachedVOffset &&
  22343. this.uScale === this._cachedUScale &&
  22344. this.vScale === this._cachedVScale &&
  22345. this.uAng === this._cachedUAng &&
  22346. this.vAng === this._cachedVAng &&
  22347. this.wAng === this._cachedWAng) {
  22348. return this._cachedTextureMatrix;
  22349. }
  22350. this._cachedUOffset = this.uOffset;
  22351. this._cachedVOffset = this.vOffset;
  22352. this._cachedUScale = this.uScale;
  22353. this._cachedVScale = this.vScale;
  22354. this._cachedUAng = this.uAng;
  22355. this._cachedVAng = this.vAng;
  22356. this._cachedWAng = this.wAng;
  22357. if (!this._cachedTextureMatrix) {
  22358. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22359. this._rowGenerationMatrix = new BABYLON.Matrix();
  22360. this._t0 = BABYLON.Vector3.Zero();
  22361. this._t1 = BABYLON.Vector3.Zero();
  22362. this._t2 = BABYLON.Vector3.Zero();
  22363. }
  22364. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  22365. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  22366. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  22367. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  22368. this._t1.subtractInPlace(this._t0);
  22369. this._t2.subtractInPlace(this._t0);
  22370. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22371. this._cachedTextureMatrix.m[0] = this._t1.x;
  22372. this._cachedTextureMatrix.m[1] = this._t1.y;
  22373. this._cachedTextureMatrix.m[2] = this._t1.z;
  22374. this._cachedTextureMatrix.m[4] = this._t2.x;
  22375. this._cachedTextureMatrix.m[5] = this._t2.y;
  22376. this._cachedTextureMatrix.m[6] = this._t2.z;
  22377. this._cachedTextureMatrix.m[8] = this._t0.x;
  22378. this._cachedTextureMatrix.m[9] = this._t0.y;
  22379. this._cachedTextureMatrix.m[10] = this._t0.z;
  22380. return this._cachedTextureMatrix;
  22381. };
  22382. Texture.prototype.getReflectionTextureMatrix = function () {
  22383. if (this.uOffset === this._cachedUOffset &&
  22384. this.vOffset === this._cachedVOffset &&
  22385. this.uScale === this._cachedUScale &&
  22386. this.vScale === this._cachedVScale &&
  22387. this.coordinatesMode === this._cachedCoordinatesMode) {
  22388. return this._cachedTextureMatrix;
  22389. }
  22390. if (!this._cachedTextureMatrix) {
  22391. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  22392. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  22393. }
  22394. this._cachedCoordinatesMode = this.coordinatesMode;
  22395. switch (this.coordinatesMode) {
  22396. case Texture.PLANAR_MODE:
  22397. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22398. this._cachedTextureMatrix[0] = this.uScale;
  22399. this._cachedTextureMatrix[5] = this.vScale;
  22400. this._cachedTextureMatrix[12] = this.uOffset;
  22401. this._cachedTextureMatrix[13] = this.vOffset;
  22402. break;
  22403. case Texture.PROJECTION_MODE:
  22404. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  22405. this._projectionModeMatrix.m[0] = 0.5;
  22406. this._projectionModeMatrix.m[5] = -0.5;
  22407. this._projectionModeMatrix.m[10] = 0.0;
  22408. this._projectionModeMatrix.m[12] = 0.5;
  22409. this._projectionModeMatrix.m[13] = 0.5;
  22410. this._projectionModeMatrix.m[14] = 1.0;
  22411. this._projectionModeMatrix.m[15] = 1.0;
  22412. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  22413. break;
  22414. default:
  22415. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  22416. break;
  22417. }
  22418. return this._cachedTextureMatrix;
  22419. };
  22420. Texture.prototype.clone = function () {
  22421. var _this = this;
  22422. return BABYLON.SerializationHelper.Clone(function () {
  22423. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  22424. }, this);
  22425. };
  22426. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  22427. get: function () {
  22428. if (!this._onLoadObservarble) {
  22429. this._onLoadObservarble = new BABYLON.Observable();
  22430. }
  22431. return this._onLoadObservarble;
  22432. },
  22433. enumerable: true,
  22434. configurable: true
  22435. });
  22436. // Statics
  22437. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  22438. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22439. if (onLoad === void 0) { onLoad = null; }
  22440. if (onError === void 0) { onError = null; }
  22441. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  22442. };
  22443. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  22444. if (parsedTexture.isCube) {
  22445. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  22446. }
  22447. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  22448. return null;
  22449. }
  22450. var texture = BABYLON.SerializationHelper.Parse(function () {
  22451. if (parsedTexture.customType) {
  22452. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  22453. return customTexture.Parse(parsedTexture, scene, rootUrl);
  22454. }
  22455. else if (parsedTexture.mirrorPlane) {
  22456. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22457. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  22458. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  22459. return mirrorTexture;
  22460. }
  22461. else if (parsedTexture.isRenderTarget) {
  22462. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  22463. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  22464. return renderTargetTexture;
  22465. }
  22466. else {
  22467. var texture;
  22468. if (parsedTexture.base64String) {
  22469. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  22470. }
  22471. else {
  22472. texture = new Texture(rootUrl + parsedTexture.name, scene);
  22473. }
  22474. return texture;
  22475. }
  22476. }, parsedTexture, scene);
  22477. // Animations
  22478. if (parsedTexture.animations) {
  22479. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22480. var parsedAnimation = parsedTexture.animations[animationIndex];
  22481. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22482. }
  22483. }
  22484. return texture;
  22485. };
  22486. // Constants
  22487. Texture.NEAREST_SAMPLINGMODE = 1;
  22488. Texture.BILINEAR_SAMPLINGMODE = 2;
  22489. Texture.TRILINEAR_SAMPLINGMODE = 3;
  22490. Texture.EXPLICIT_MODE = 0;
  22491. Texture.SPHERICAL_MODE = 1;
  22492. Texture.PLANAR_MODE = 2;
  22493. Texture.CUBIC_MODE = 3;
  22494. Texture.PROJECTION_MODE = 4;
  22495. Texture.SKYBOX_MODE = 5;
  22496. Texture.INVCUBIC_MODE = 6;
  22497. Texture.EQUIRECTANGULAR_MODE = 7;
  22498. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  22499. Texture.CLAMP_ADDRESSMODE = 0;
  22500. Texture.WRAP_ADDRESSMODE = 1;
  22501. Texture.MIRROR_ADDRESSMODE = 2;
  22502. __decorate([
  22503. BABYLON.serialize()
  22504. ], Texture.prototype, "url", void 0);
  22505. __decorate([
  22506. BABYLON.serialize()
  22507. ], Texture.prototype, "uOffset", void 0);
  22508. __decorate([
  22509. BABYLON.serialize()
  22510. ], Texture.prototype, "vOffset", void 0);
  22511. __decorate([
  22512. BABYLON.serialize()
  22513. ], Texture.prototype, "uScale", void 0);
  22514. __decorate([
  22515. BABYLON.serialize()
  22516. ], Texture.prototype, "vScale", void 0);
  22517. __decorate([
  22518. BABYLON.serialize()
  22519. ], Texture.prototype, "uAng", void 0);
  22520. __decorate([
  22521. BABYLON.serialize()
  22522. ], Texture.prototype, "vAng", void 0);
  22523. __decorate([
  22524. BABYLON.serialize()
  22525. ], Texture.prototype, "wAng", void 0);
  22526. return Texture;
  22527. }(BABYLON.BaseTexture));
  22528. BABYLON.Texture = Texture;
  22529. })(BABYLON || (BABYLON = {}));
  22530. var BABYLON;
  22531. (function (BABYLON) {
  22532. var CubeTexture = (function (_super) {
  22533. __extends(CubeTexture, _super);
  22534. function CubeTexture(rootUrl, scene, extensions, noMipmap, files) {
  22535. _super.call(this, scene);
  22536. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  22537. this.name = rootUrl;
  22538. this.url = rootUrl;
  22539. this._noMipmap = noMipmap;
  22540. this.hasAlpha = false;
  22541. if (!rootUrl && !files) {
  22542. return;
  22543. }
  22544. this._texture = this._getFromCache(rootUrl, noMipmap);
  22545. if (!files) {
  22546. if (!extensions) {
  22547. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  22548. }
  22549. files = [];
  22550. for (var index = 0; index < extensions.length; index++) {
  22551. files.push(rootUrl + extensions[index]);
  22552. }
  22553. this._extensions = extensions;
  22554. }
  22555. this._files = files;
  22556. if (!this._texture) {
  22557. if (!scene.useDelayedTextureLoading) {
  22558. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap);
  22559. }
  22560. else {
  22561. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22562. }
  22563. }
  22564. this.isCube = true;
  22565. this._textureMatrix = BABYLON.Matrix.Identity();
  22566. }
  22567. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  22568. return new CubeTexture("", scene, null, noMipmap, files);
  22569. };
  22570. // Methods
  22571. CubeTexture.prototype.delayLoad = function () {
  22572. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22573. return;
  22574. }
  22575. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22576. this._texture = this._getFromCache(this.url, this._noMipmap);
  22577. if (!this._texture) {
  22578. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  22579. }
  22580. };
  22581. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  22582. return this._textureMatrix;
  22583. };
  22584. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  22585. var texture = BABYLON.SerializationHelper.Parse(function () {
  22586. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  22587. }, parsedTexture, scene);
  22588. // Animations
  22589. if (parsedTexture.animations) {
  22590. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  22591. var parsedAnimation = parsedTexture.animations[animationIndex];
  22592. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22593. }
  22594. }
  22595. return texture;
  22596. };
  22597. CubeTexture.prototype.clone = function () {
  22598. var _this = this;
  22599. return BABYLON.SerializationHelper.Clone(function () {
  22600. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  22601. }, this);
  22602. };
  22603. return CubeTexture;
  22604. }(BABYLON.BaseTexture));
  22605. BABYLON.CubeTexture = CubeTexture;
  22606. })(BABYLON || (BABYLON = {}));
  22607. var BABYLON;
  22608. (function (BABYLON) {
  22609. var RenderTargetTexture = (function (_super) {
  22610. __extends(RenderTargetTexture, _super);
  22611. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  22612. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  22613. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  22614. if (isCube === void 0) { isCube = false; }
  22615. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  22616. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  22617. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  22618. _super.call(this, null, scene, !generateMipMaps);
  22619. this.isCube = isCube;
  22620. /**
  22621. * Use this list to define the list of mesh you want to render.
  22622. */
  22623. this.renderList = new Array();
  22624. this.renderParticles = true;
  22625. this.renderSprites = false;
  22626. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  22627. // Events
  22628. /**
  22629. * An event triggered when the texture is unbind.
  22630. * @type {BABYLON.Observable}
  22631. */
  22632. this.onAfterUnbindObservable = new BABYLON.Observable();
  22633. /**
  22634. * An event triggered before rendering the texture
  22635. * @type {BABYLON.Observable}
  22636. */
  22637. this.onBeforeRenderObservable = new BABYLON.Observable();
  22638. /**
  22639. * An event triggered after rendering the texture
  22640. * @type {BABYLON.Observable}
  22641. */
  22642. this.onAfterRenderObservable = new BABYLON.Observable();
  22643. /**
  22644. * An event triggered after the texture clear
  22645. * @type {BABYLON.Observable}
  22646. */
  22647. this.onClearObservable = new BABYLON.Observable();
  22648. this._currentRefreshId = -1;
  22649. this._refreshRate = 1;
  22650. this.name = name;
  22651. this.isRenderTarget = true;
  22652. this._size = size;
  22653. this._generateMipMaps = generateMipMaps;
  22654. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  22655. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  22656. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22657. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  22658. }
  22659. if (isCube) {
  22660. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  22661. generateMipMaps: generateMipMaps,
  22662. samplingMode: samplingMode,
  22663. generateDepthBuffer: generateDepthBuffer,
  22664. generateStencilBuffer: generateStencilBuffer
  22665. });
  22666. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  22667. this._textureMatrix = BABYLON.Matrix.Identity();
  22668. }
  22669. else {
  22670. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  22671. generateMipMaps: generateMipMaps,
  22672. type: type,
  22673. samplingMode: samplingMode,
  22674. generateDepthBuffer: generateDepthBuffer,
  22675. generateStencilBuffer: generateStencilBuffer
  22676. });
  22677. }
  22678. // Rendering groups
  22679. this._renderingManager = new BABYLON.RenderingManager(scene);
  22680. }
  22681. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  22682. get: function () {
  22683. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  22684. },
  22685. enumerable: true,
  22686. configurable: true
  22687. });
  22688. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  22689. get: function () {
  22690. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  22691. },
  22692. enumerable: true,
  22693. configurable: true
  22694. });
  22695. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  22696. get: function () {
  22697. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  22698. },
  22699. enumerable: true,
  22700. configurable: true
  22701. });
  22702. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  22703. set: function (callback) {
  22704. if (this._onAfterUnbindObserver) {
  22705. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  22706. }
  22707. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  22708. },
  22709. enumerable: true,
  22710. configurable: true
  22711. });
  22712. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  22713. set: function (callback) {
  22714. if (this._onBeforeRenderObserver) {
  22715. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22716. }
  22717. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22718. },
  22719. enumerable: true,
  22720. configurable: true
  22721. });
  22722. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  22723. set: function (callback) {
  22724. if (this._onAfterRenderObserver) {
  22725. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22726. }
  22727. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22728. },
  22729. enumerable: true,
  22730. configurable: true
  22731. });
  22732. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  22733. set: function (callback) {
  22734. if (this._onClearObserver) {
  22735. this.onClearObservable.remove(this._onClearObserver);
  22736. }
  22737. this._onClearObserver = this.onClearObservable.add(callback);
  22738. },
  22739. enumerable: true,
  22740. configurable: true
  22741. });
  22742. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  22743. this._currentRefreshId = -1;
  22744. };
  22745. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  22746. get: function () {
  22747. return this._refreshRate;
  22748. },
  22749. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  22750. set: function (value) {
  22751. this._refreshRate = value;
  22752. this.resetRefreshCounter();
  22753. },
  22754. enumerable: true,
  22755. configurable: true
  22756. });
  22757. RenderTargetTexture.prototype._shouldRender = function () {
  22758. if (this._currentRefreshId === -1) {
  22759. this._currentRefreshId = 1;
  22760. return true;
  22761. }
  22762. if (this.refreshRate === this._currentRefreshId) {
  22763. this._currentRefreshId = 1;
  22764. return true;
  22765. }
  22766. this._currentRefreshId++;
  22767. return false;
  22768. };
  22769. RenderTargetTexture.prototype.isReady = function () {
  22770. if (!this.getScene().renderTargetsEnabled) {
  22771. return false;
  22772. }
  22773. return _super.prototype.isReady.call(this);
  22774. };
  22775. RenderTargetTexture.prototype.getRenderSize = function () {
  22776. return this._size;
  22777. };
  22778. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  22779. get: function () {
  22780. return true;
  22781. },
  22782. enumerable: true,
  22783. configurable: true
  22784. });
  22785. RenderTargetTexture.prototype.scale = function (ratio) {
  22786. var newSize = this._size * ratio;
  22787. this.resize(newSize, this._generateMipMaps);
  22788. };
  22789. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  22790. if (this.isCube) {
  22791. return this._textureMatrix;
  22792. }
  22793. return _super.prototype.getReflectionTextureMatrix.call(this);
  22794. };
  22795. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  22796. this.releaseInternalTexture();
  22797. if (this.isCube) {
  22798. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  22799. }
  22800. else {
  22801. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  22802. }
  22803. };
  22804. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  22805. var scene = this.getScene();
  22806. if (this.useCameraPostProcesses !== undefined) {
  22807. useCameraPostProcess = this.useCameraPostProcesses;
  22808. }
  22809. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22810. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  22811. }
  22812. if (this._waitingRenderList) {
  22813. this.renderList = [];
  22814. for (var index = 0; index < this._waitingRenderList.length; index++) {
  22815. var id = this._waitingRenderList[index];
  22816. this.renderList.push(scene.getMeshByID(id));
  22817. }
  22818. delete this._waitingRenderList;
  22819. }
  22820. // Is predicate defined?
  22821. if (this.renderListPredicate) {
  22822. this.renderList.splice(0); // Clear previous renderList
  22823. var sceneMeshes = this.getScene().meshes;
  22824. for (var index = 0; index < sceneMeshes.length; index++) {
  22825. var mesh = sceneMeshes[index];
  22826. if (this.renderListPredicate(mesh)) {
  22827. this.renderList.push(mesh);
  22828. }
  22829. }
  22830. }
  22831. if (this.renderList && this.renderList.length === 0) {
  22832. return;
  22833. }
  22834. // Prepare renderingManager
  22835. this._renderingManager.reset();
  22836. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  22837. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  22838. var sceneRenderId = scene.getRenderId();
  22839. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  22840. var mesh = currentRenderList[meshIndex];
  22841. if (mesh) {
  22842. if (!mesh.isReady()) {
  22843. // Reset _currentRefreshId
  22844. this.resetRefreshCounter();
  22845. continue;
  22846. }
  22847. mesh._preActivateForIntermediateRendering(sceneRenderId);
  22848. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  22849. mesh._activate(sceneRenderId);
  22850. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  22851. var subMesh = mesh.subMeshes[subIndex];
  22852. scene._activeIndices.addCount(subMesh.indexCount, false);
  22853. this._renderingManager.dispatch(subMesh);
  22854. }
  22855. }
  22856. }
  22857. }
  22858. if (this.isCube) {
  22859. for (var face = 0; face < 6; face++) {
  22860. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22861. scene.incrementRenderId();
  22862. scene.resetCachedMaterial();
  22863. }
  22864. }
  22865. else {
  22866. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  22867. }
  22868. this.onAfterUnbindObservable.notifyObservers(this);
  22869. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  22870. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  22871. }
  22872. scene.resetCachedMaterial();
  22873. };
  22874. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  22875. var scene = this.getScene();
  22876. var engine = scene.getEngine();
  22877. // Bind
  22878. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  22879. if (this.isCube) {
  22880. engine.bindFramebuffer(this._texture, faceIndex);
  22881. }
  22882. else {
  22883. engine.bindFramebuffer(this._texture);
  22884. }
  22885. }
  22886. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  22887. // Clear
  22888. if (this.onClearObservable.hasObservers()) {
  22889. this.onClearObservable.notifyObservers(engine);
  22890. }
  22891. else {
  22892. engine.clear(scene.clearColor, true, true, true);
  22893. }
  22894. if (!this._doNotChangeAspectRatio) {
  22895. scene.updateTransformMatrix(true);
  22896. }
  22897. // Render
  22898. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  22899. if (useCameraPostProcess) {
  22900. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  22901. }
  22902. if (!this._doNotChangeAspectRatio) {
  22903. scene.updateTransformMatrix(true);
  22904. }
  22905. this.onAfterRenderObservable.notifyObservers(faceIndex);
  22906. // Dump ?
  22907. if (dumpForDebug) {
  22908. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  22909. }
  22910. // Unbind
  22911. if (!this.isCube || faceIndex === 5) {
  22912. if (this.isCube) {
  22913. if (faceIndex === 5) {
  22914. engine.generateMipMapsForCubemap(this._texture);
  22915. }
  22916. }
  22917. engine.unBindFramebuffer(this._texture, this.isCube);
  22918. }
  22919. };
  22920. /**
  22921. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22922. * This allowed control for front to back rendering or reversly depending of the special needs.
  22923. *
  22924. * @param renderingGroupId The rendering group id corresponding to its index
  22925. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22926. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22927. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22928. */
  22929. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22930. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22931. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22932. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22933. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  22934. };
  22935. /**
  22936. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22937. *
  22938. * @param renderingGroupId The rendering group id corresponding to its index
  22939. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22940. */
  22941. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  22942. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  22943. };
  22944. RenderTargetTexture.prototype.clone = function () {
  22945. var textureSize = this.getSize();
  22946. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  22947. // Base texture
  22948. newTexture.hasAlpha = this.hasAlpha;
  22949. newTexture.level = this.level;
  22950. // RenderTarget Texture
  22951. newTexture.coordinatesMode = this.coordinatesMode;
  22952. newTexture.renderList = this.renderList.slice(0);
  22953. return newTexture;
  22954. };
  22955. RenderTargetTexture.prototype.serialize = function () {
  22956. if (!this.name) {
  22957. return null;
  22958. }
  22959. var serializationObject = _super.prototype.serialize.call(this);
  22960. serializationObject.renderTargetSize = this.getRenderSize();
  22961. serializationObject.renderList = [];
  22962. for (var index = 0; index < this.renderList.length; index++) {
  22963. serializationObject.renderList.push(this.renderList[index].id);
  22964. }
  22965. return serializationObject;
  22966. };
  22967. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  22968. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  22969. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  22970. return RenderTargetTexture;
  22971. }(BABYLON.Texture));
  22972. BABYLON.RenderTargetTexture = RenderTargetTexture;
  22973. })(BABYLON || (BABYLON = {}));
  22974. var BABYLON;
  22975. (function (BABYLON) {
  22976. var ProceduralTexture = (function (_super) {
  22977. __extends(ProceduralTexture, _super);
  22978. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  22979. if (generateMipMaps === void 0) { generateMipMaps = true; }
  22980. if (isCube === void 0) { isCube = false; }
  22981. _super.call(this, null, scene, !generateMipMaps);
  22982. this.isCube = isCube;
  22983. this.isEnabled = true;
  22984. this._currentRefreshId = -1;
  22985. this._refreshRate = 1;
  22986. this._vertexBuffers = {};
  22987. this._uniforms = new Array();
  22988. this._samplers = new Array();
  22989. this._textures = new Array();
  22990. this._floats = new Array();
  22991. this._floatsArrays = {};
  22992. this._colors3 = new Array();
  22993. this._colors4 = new Array();
  22994. this._vectors2 = new Array();
  22995. this._vectors3 = new Array();
  22996. this._matrices = new Array();
  22997. this._fallbackTextureUsed = false;
  22998. scene._proceduralTextures.push(this);
  22999. this.name = name;
  23000. this.isRenderTarget = true;
  23001. this._size = size;
  23002. this._generateMipMaps = generateMipMaps;
  23003. this.setFragment(fragment);
  23004. this._fallbackTexture = fallbackTexture;
  23005. var engine = scene.getEngine();
  23006. if (isCube) {
  23007. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  23008. this.setFloat("face", 0);
  23009. }
  23010. else {
  23011. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  23012. }
  23013. // VBO
  23014. var vertices = [];
  23015. vertices.push(1, 1);
  23016. vertices.push(-1, 1);
  23017. vertices.push(-1, -1);
  23018. vertices.push(1, -1);
  23019. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  23020. // Indices
  23021. var indices = [];
  23022. indices.push(0);
  23023. indices.push(1);
  23024. indices.push(2);
  23025. indices.push(0);
  23026. indices.push(2);
  23027. indices.push(3);
  23028. this._indexBuffer = engine.createIndexBuffer(indices);
  23029. }
  23030. ProceduralTexture.prototype.reset = function () {
  23031. if (this._effect === undefined) {
  23032. return;
  23033. }
  23034. var engine = this.getScene().getEngine();
  23035. engine._releaseEffect(this._effect);
  23036. };
  23037. ProceduralTexture.prototype.isReady = function () {
  23038. var _this = this;
  23039. var engine = this.getScene().getEngine();
  23040. var shaders;
  23041. if (!this._fragment) {
  23042. return false;
  23043. }
  23044. if (this._fallbackTextureUsed) {
  23045. return true;
  23046. }
  23047. if (this._fragment.fragmentElement !== undefined) {
  23048. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  23049. }
  23050. else {
  23051. shaders = { vertex: "procedural", fragment: this._fragment };
  23052. }
  23053. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  23054. _this.releaseInternalTexture();
  23055. if (_this._fallbackTexture) {
  23056. _this._texture = _this._fallbackTexture._texture;
  23057. _this._texture.references++;
  23058. }
  23059. _this._fallbackTextureUsed = true;
  23060. });
  23061. return this._effect.isReady();
  23062. };
  23063. ProceduralTexture.prototype.resetRefreshCounter = function () {
  23064. this._currentRefreshId = -1;
  23065. };
  23066. ProceduralTexture.prototype.setFragment = function (fragment) {
  23067. this._fragment = fragment;
  23068. };
  23069. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  23070. get: function () {
  23071. return this._refreshRate;
  23072. },
  23073. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23074. set: function (value) {
  23075. this._refreshRate = value;
  23076. this.resetRefreshCounter();
  23077. },
  23078. enumerable: true,
  23079. configurable: true
  23080. });
  23081. ProceduralTexture.prototype._shouldRender = function () {
  23082. if (!this.isEnabled || !this.isReady() || !this._texture) {
  23083. return false;
  23084. }
  23085. if (this._fallbackTextureUsed) {
  23086. return false;
  23087. }
  23088. if (this._currentRefreshId === -1) {
  23089. this._currentRefreshId = 1;
  23090. return true;
  23091. }
  23092. if (this.refreshRate === this._currentRefreshId) {
  23093. this._currentRefreshId = 1;
  23094. return true;
  23095. }
  23096. this._currentRefreshId++;
  23097. return false;
  23098. };
  23099. ProceduralTexture.prototype.getRenderSize = function () {
  23100. return this._size;
  23101. };
  23102. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  23103. if (this._fallbackTextureUsed) {
  23104. return;
  23105. }
  23106. this.releaseInternalTexture();
  23107. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23108. };
  23109. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  23110. if (this._uniforms.indexOf(uniformName) === -1) {
  23111. this._uniforms.push(uniformName);
  23112. }
  23113. };
  23114. ProceduralTexture.prototype.setTexture = function (name, texture) {
  23115. if (this._samplers.indexOf(name) === -1) {
  23116. this._samplers.push(name);
  23117. }
  23118. this._textures[name] = texture;
  23119. return this;
  23120. };
  23121. ProceduralTexture.prototype.setFloat = function (name, value) {
  23122. this._checkUniform(name);
  23123. this._floats[name] = value;
  23124. return this;
  23125. };
  23126. ProceduralTexture.prototype.setFloats = function (name, value) {
  23127. this._checkUniform(name);
  23128. this._floatsArrays[name] = value;
  23129. return this;
  23130. };
  23131. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23132. this._checkUniform(name);
  23133. this._colors3[name] = value;
  23134. return this;
  23135. };
  23136. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23137. this._checkUniform(name);
  23138. this._colors4[name] = value;
  23139. return this;
  23140. };
  23141. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23142. this._checkUniform(name);
  23143. this._vectors2[name] = value;
  23144. return this;
  23145. };
  23146. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23147. this._checkUniform(name);
  23148. this._vectors3[name] = value;
  23149. return this;
  23150. };
  23151. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23152. this._checkUniform(name);
  23153. this._matrices[name] = value;
  23154. return this;
  23155. };
  23156. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23157. var scene = this.getScene();
  23158. var engine = scene.getEngine();
  23159. // Render
  23160. engine.enableEffect(this._effect);
  23161. engine.setState(false);
  23162. // Texture
  23163. for (var name in this._textures) {
  23164. this._effect.setTexture(name, this._textures[name]);
  23165. }
  23166. // Float
  23167. for (name in this._floats) {
  23168. this._effect.setFloat(name, this._floats[name]);
  23169. }
  23170. // Floats
  23171. for (name in this._floatsArrays) {
  23172. this._effect.setArray(name, this._floatsArrays[name]);
  23173. }
  23174. // Color3
  23175. for (name in this._colors3) {
  23176. this._effect.setColor3(name, this._colors3[name]);
  23177. }
  23178. // Color4
  23179. for (name in this._colors4) {
  23180. var color = this._colors4[name];
  23181. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23182. }
  23183. // Vector2
  23184. for (name in this._vectors2) {
  23185. this._effect.setVector2(name, this._vectors2[name]);
  23186. }
  23187. // Vector3
  23188. for (name in this._vectors3) {
  23189. this._effect.setVector3(name, this._vectors3[name]);
  23190. }
  23191. // Matrix
  23192. for (name in this._matrices) {
  23193. this._effect.setMatrix(name, this._matrices[name]);
  23194. }
  23195. // VBOs
  23196. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23197. if (this.isCube) {
  23198. for (var face = 0; face < 6; face++) {
  23199. engine.bindFramebuffer(this._texture, face);
  23200. this._effect.setFloat("face", face);
  23201. // Clear
  23202. engine.clear(scene.clearColor, true, true, true);
  23203. // Draw order
  23204. engine.draw(true, 0, 6);
  23205. // Mipmaps
  23206. if (face === 5) {
  23207. engine.generateMipMapsForCubemap(this._texture);
  23208. }
  23209. }
  23210. }
  23211. else {
  23212. engine.bindFramebuffer(this._texture);
  23213. // Clear
  23214. engine.clear(scene.clearColor, true, true, true);
  23215. // Draw order
  23216. engine.draw(true, 0, 6);
  23217. }
  23218. // Unbind
  23219. engine.unBindFramebuffer(this._texture, this.isCube);
  23220. if (this.onGenerated) {
  23221. this.onGenerated();
  23222. }
  23223. };
  23224. ProceduralTexture.prototype.clone = function () {
  23225. var textureSize = this.getSize();
  23226. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23227. // Base texture
  23228. newTexture.hasAlpha = this.hasAlpha;
  23229. newTexture.level = this.level;
  23230. // RenderTarget Texture
  23231. newTexture.coordinatesMode = this.coordinatesMode;
  23232. return newTexture;
  23233. };
  23234. ProceduralTexture.prototype.dispose = function () {
  23235. var index = this.getScene()._proceduralTextures.indexOf(this);
  23236. if (index >= 0) {
  23237. this.getScene()._proceduralTextures.splice(index, 1);
  23238. }
  23239. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23240. if (vertexBuffer) {
  23241. vertexBuffer.dispose();
  23242. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23243. }
  23244. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23245. this._indexBuffer = null;
  23246. }
  23247. _super.prototype.dispose.call(this);
  23248. };
  23249. return ProceduralTexture;
  23250. }(BABYLON.Texture));
  23251. BABYLON.ProceduralTexture = ProceduralTexture;
  23252. })(BABYLON || (BABYLON = {}));
  23253. var BABYLON;
  23254. (function (BABYLON) {
  23255. var MirrorTexture = (function (_super) {
  23256. __extends(MirrorTexture, _super);
  23257. function MirrorTexture(name, size, scene, generateMipMaps) {
  23258. var _this = this;
  23259. _super.call(this, name, size, scene, generateMipMaps, true);
  23260. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  23261. this._transformMatrix = BABYLON.Matrix.Zero();
  23262. this._mirrorMatrix = BABYLON.Matrix.Zero();
  23263. this.onBeforeRenderObservable.add(function () {
  23264. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  23265. _this._savedViewMatrix = scene.getViewMatrix();
  23266. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  23267. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  23268. scene.clipPlane = _this.mirrorPlane;
  23269. scene.getEngine().cullBackFaces = false;
  23270. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  23271. });
  23272. this.onAfterRenderObservable.add(function () {
  23273. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  23274. scene.getEngine().cullBackFaces = true;
  23275. scene._mirroredCameraPosition = null;
  23276. delete scene.clipPlane;
  23277. });
  23278. }
  23279. MirrorTexture.prototype.clone = function () {
  23280. var textureSize = this.getSize();
  23281. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23282. // Base texture
  23283. newTexture.hasAlpha = this.hasAlpha;
  23284. newTexture.level = this.level;
  23285. // Mirror Texture
  23286. newTexture.mirrorPlane = this.mirrorPlane.clone();
  23287. newTexture.renderList = this.renderList.slice(0);
  23288. return newTexture;
  23289. };
  23290. MirrorTexture.prototype.serialize = function () {
  23291. if (!this.name) {
  23292. return null;
  23293. }
  23294. var serializationObject = _super.prototype.serialize.call(this);
  23295. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  23296. return serializationObject;
  23297. };
  23298. return MirrorTexture;
  23299. }(BABYLON.RenderTargetTexture));
  23300. BABYLON.MirrorTexture = MirrorTexture;
  23301. })(BABYLON || (BABYLON = {}));
  23302. var BABYLON;
  23303. (function (BABYLON) {
  23304. /**
  23305. * Creates a refraction texture used by refraction channel of the standard material.
  23306. * @param name the texture name
  23307. * @param size size of the underlying texture
  23308. * @param scene root scene
  23309. */
  23310. var RefractionTexture = (function (_super) {
  23311. __extends(RefractionTexture, _super);
  23312. function RefractionTexture(name, size, scene, generateMipMaps) {
  23313. var _this = this;
  23314. _super.call(this, name, size, scene, generateMipMaps, true);
  23315. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  23316. this.depth = 2.0;
  23317. this.onBeforeRenderObservable.add(function () {
  23318. scene.clipPlane = _this.refractionPlane;
  23319. });
  23320. this.onAfterRenderObservable.add(function () {
  23321. delete scene.clipPlane;
  23322. });
  23323. }
  23324. RefractionTexture.prototype.clone = function () {
  23325. var textureSize = this.getSize();
  23326. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23327. // Base texture
  23328. newTexture.hasAlpha = this.hasAlpha;
  23329. newTexture.level = this.level;
  23330. // Refraction Texture
  23331. newTexture.refractionPlane = this.refractionPlane.clone();
  23332. newTexture.renderList = this.renderList.slice(0);
  23333. newTexture.depth = this.depth;
  23334. return newTexture;
  23335. };
  23336. RefractionTexture.prototype.serialize = function () {
  23337. if (!this.name) {
  23338. return null;
  23339. }
  23340. var serializationObject = _super.prototype.serialize.call(this);
  23341. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  23342. serializationObject.depth = this.depth;
  23343. return serializationObject;
  23344. };
  23345. return RefractionTexture;
  23346. }(BABYLON.RenderTargetTexture));
  23347. BABYLON.RefractionTexture = RefractionTexture;
  23348. })(BABYLON || (BABYLON = {}));
  23349. var BABYLON;
  23350. (function (BABYLON) {
  23351. var DynamicTexture = (function (_super) {
  23352. __extends(DynamicTexture, _super);
  23353. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  23354. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23355. _super.call(this, null, scene, !generateMipMaps);
  23356. this.name = name;
  23357. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23358. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23359. this._generateMipMaps = generateMipMaps;
  23360. if (options.getContext) {
  23361. this._canvas = options;
  23362. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23363. }
  23364. else {
  23365. this._canvas = document.createElement("canvas");
  23366. if (options.width) {
  23367. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  23368. }
  23369. else {
  23370. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  23371. }
  23372. }
  23373. var textureSize = this.getSize();
  23374. this._canvas.width = textureSize.width;
  23375. this._canvas.height = textureSize.height;
  23376. this._context = this._canvas.getContext("2d");
  23377. }
  23378. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  23379. get: function () {
  23380. return true;
  23381. },
  23382. enumerable: true,
  23383. configurable: true
  23384. });
  23385. DynamicTexture.prototype.scale = function (ratio) {
  23386. var textureSize = this.getSize();
  23387. textureSize.width *= ratio;
  23388. textureSize.height *= ratio;
  23389. this._canvas.width = textureSize.width;
  23390. this._canvas.height = textureSize.height;
  23391. this.releaseInternalTexture();
  23392. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  23393. };
  23394. DynamicTexture.prototype.getContext = function () {
  23395. return this._context;
  23396. };
  23397. DynamicTexture.prototype.clear = function () {
  23398. var size = this.getSize();
  23399. this._context.fillRect(0, 0, size.width, size.height);
  23400. };
  23401. DynamicTexture.prototype.update = function (invertY) {
  23402. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  23403. };
  23404. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  23405. if (update === void 0) { update = true; }
  23406. var size = this.getSize();
  23407. if (clearColor) {
  23408. this._context.fillStyle = clearColor;
  23409. this._context.fillRect(0, 0, size.width, size.height);
  23410. }
  23411. this._context.font = font;
  23412. if (x === null) {
  23413. var textSize = this._context.measureText(text);
  23414. x = (size.width - textSize.width) / 2;
  23415. }
  23416. this._context.fillStyle = color;
  23417. this._context.fillText(text, x, y);
  23418. if (update) {
  23419. this.update(invertY);
  23420. }
  23421. };
  23422. DynamicTexture.prototype.clone = function () {
  23423. var textureSize = this.getSize();
  23424. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  23425. // Base texture
  23426. newTexture.hasAlpha = this.hasAlpha;
  23427. newTexture.level = this.level;
  23428. // Dynamic Texture
  23429. newTexture.wrapU = this.wrapU;
  23430. newTexture.wrapV = this.wrapV;
  23431. return newTexture;
  23432. };
  23433. return DynamicTexture;
  23434. }(BABYLON.Texture));
  23435. BABYLON.DynamicTexture = DynamicTexture;
  23436. })(BABYLON || (BABYLON = {}));
  23437. var BABYLON;
  23438. (function (BABYLON) {
  23439. var VideoTexture = (function (_super) {
  23440. __extends(VideoTexture, _super);
  23441. /**
  23442. * Creates a video texture.
  23443. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  23444. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  23445. * @param {BABYLON.Scene} scene is obviously the current scene.
  23446. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  23447. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  23448. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  23449. */
  23450. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  23451. var _this = this;
  23452. if (generateMipMaps === void 0) { generateMipMaps = false; }
  23453. if (invertY === void 0) { invertY = false; }
  23454. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23455. _super.call(this, null, scene, !generateMipMaps, invertY);
  23456. this._autoLaunch = true;
  23457. var urls;
  23458. this.name = name;
  23459. if (urlsOrVideo instanceof HTMLVideoElement) {
  23460. this.video = urlsOrVideo;
  23461. }
  23462. else {
  23463. urls = urlsOrVideo;
  23464. this.video = document.createElement("video");
  23465. this.video.autoplay = false;
  23466. this.video.loop = true;
  23467. }
  23468. this._generateMipMaps = generateMipMaps;
  23469. this._samplingMode = samplingMode;
  23470. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  23471. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23472. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23473. }
  23474. else {
  23475. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23476. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23477. this._generateMipMaps = false;
  23478. }
  23479. if (urls) {
  23480. this.video.addEventListener("canplaythrough", function () {
  23481. _this._createTexture();
  23482. });
  23483. urls.forEach(function (url) {
  23484. var source = document.createElement("source");
  23485. source.src = url;
  23486. _this.video.appendChild(source);
  23487. });
  23488. }
  23489. else {
  23490. this._createTexture();
  23491. }
  23492. this._lastUpdate = BABYLON.Tools.Now;
  23493. }
  23494. VideoTexture.prototype._createTexture = function () {
  23495. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  23496. this._texture.isReady = true;
  23497. };
  23498. VideoTexture.prototype.update = function () {
  23499. if (this._autoLaunch) {
  23500. this._autoLaunch = false;
  23501. this.video.play();
  23502. }
  23503. var now = BABYLON.Tools.Now;
  23504. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  23505. return false;
  23506. }
  23507. this._lastUpdate = now;
  23508. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  23509. return true;
  23510. };
  23511. return VideoTexture;
  23512. }(BABYLON.Texture));
  23513. BABYLON.VideoTexture = VideoTexture;
  23514. })(BABYLON || (BABYLON = {}));
  23515. var BABYLON;
  23516. (function (BABYLON) {
  23517. var CustomProceduralTexture = (function (_super) {
  23518. __extends(CustomProceduralTexture, _super);
  23519. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  23520. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  23521. this._animate = true;
  23522. this._time = 0;
  23523. this._texturePath = texturePath;
  23524. //Try to load json
  23525. this.loadJson(texturePath);
  23526. this.refreshRate = 1;
  23527. }
  23528. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  23529. var _this = this;
  23530. var that = this;
  23531. function noConfigFile() {
  23532. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  23533. try {
  23534. that.setFragment(that._texturePath);
  23535. }
  23536. catch (ex) {
  23537. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  23538. }
  23539. }
  23540. var configFileUrl = jsonUrl + "/config.json";
  23541. var xhr = new XMLHttpRequest();
  23542. xhr.open("GET", configFileUrl, true);
  23543. xhr.addEventListener("load", function () {
  23544. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  23545. try {
  23546. _this._config = JSON.parse(xhr.response);
  23547. _this.updateShaderUniforms();
  23548. _this.updateTextures();
  23549. _this.setFragment(_this._texturePath + "/custom");
  23550. _this._animate = _this._config.animate;
  23551. _this.refreshRate = _this._config.refreshrate;
  23552. }
  23553. catch (ex) {
  23554. noConfigFile();
  23555. }
  23556. }
  23557. else {
  23558. noConfigFile();
  23559. }
  23560. }, false);
  23561. xhr.addEventListener("error", function () {
  23562. noConfigFile();
  23563. }, false);
  23564. try {
  23565. xhr.send();
  23566. }
  23567. catch (ex) {
  23568. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  23569. }
  23570. };
  23571. CustomProceduralTexture.prototype.isReady = function () {
  23572. if (!_super.prototype.isReady.call(this)) {
  23573. return false;
  23574. }
  23575. for (var name in this._textures) {
  23576. var texture = this._textures[name];
  23577. if (!texture.isReady()) {
  23578. return false;
  23579. }
  23580. }
  23581. return true;
  23582. };
  23583. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23584. if (this._animate) {
  23585. this._time += this.getScene().getAnimationRatio() * 0.03;
  23586. this.updateShaderUniforms();
  23587. }
  23588. _super.prototype.render.call(this, useCameraPostProcess);
  23589. };
  23590. CustomProceduralTexture.prototype.updateTextures = function () {
  23591. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  23592. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  23593. }
  23594. };
  23595. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  23596. if (this._config) {
  23597. for (var j = 0; j < this._config.uniforms.length; j++) {
  23598. var uniform = this._config.uniforms[j];
  23599. switch (uniform.type) {
  23600. case "float":
  23601. this.setFloat(uniform.name, uniform.value);
  23602. break;
  23603. case "color3":
  23604. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  23605. break;
  23606. case "color4":
  23607. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  23608. break;
  23609. case "vector2":
  23610. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  23611. break;
  23612. case "vector3":
  23613. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  23614. break;
  23615. }
  23616. }
  23617. }
  23618. this.setFloat("time", this._time);
  23619. };
  23620. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  23621. get: function () {
  23622. return this._animate;
  23623. },
  23624. set: function (value) {
  23625. this._animate = value;
  23626. },
  23627. enumerable: true,
  23628. configurable: true
  23629. });
  23630. return CustomProceduralTexture;
  23631. }(BABYLON.ProceduralTexture));
  23632. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  23633. })(BABYLON || (BABYLON = {}));
  23634. var BABYLON;
  23635. (function (BABYLON) {
  23636. var EffectFallbacks = (function () {
  23637. function EffectFallbacks() {
  23638. this._defines = {};
  23639. this._currentRank = 32;
  23640. this._maxRank = -1;
  23641. }
  23642. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23643. if (!this._defines[rank]) {
  23644. if (rank < this._currentRank) {
  23645. this._currentRank = rank;
  23646. }
  23647. if (rank > this._maxRank) {
  23648. this._maxRank = rank;
  23649. }
  23650. this._defines[rank] = new Array();
  23651. }
  23652. this._defines[rank].push(define);
  23653. };
  23654. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23655. this._meshRank = rank;
  23656. this._mesh = mesh;
  23657. if (rank > this._maxRank) {
  23658. this._maxRank = rank;
  23659. }
  23660. };
  23661. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23662. get: function () {
  23663. return this._currentRank <= this._maxRank;
  23664. },
  23665. enumerable: true,
  23666. configurable: true
  23667. });
  23668. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23669. var currentFallbacks = this._defines[this._currentRank];
  23670. for (var index = 0; index < currentFallbacks.length; index++) {
  23671. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23672. }
  23673. if (this._mesh && this._currentRank === this._meshRank) {
  23674. this._mesh.computeBonesUsingShaders = false;
  23675. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23676. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23677. }
  23678. this._currentRank++;
  23679. return currentDefines;
  23680. };
  23681. return EffectFallbacks;
  23682. }());
  23683. BABYLON.EffectFallbacks = EffectFallbacks;
  23684. var Effect = (function () {
  23685. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23686. var _this = this;
  23687. this._isReady = false;
  23688. this._compilationError = "";
  23689. this._valueCache = {};
  23690. this._engine = engine;
  23691. this.name = baseName;
  23692. this.defines = defines;
  23693. this._uniformsNames = uniformsNames.concat(samplers);
  23694. this._samplers = samplers;
  23695. this._attributesNames = attributesNames;
  23696. this.onError = onError;
  23697. this.onCompiled = onCompiled;
  23698. this._indexParameters = indexParameters;
  23699. var vertexSource;
  23700. var fragmentSource;
  23701. if (baseName.vertexElement) {
  23702. vertexSource = document.getElementById(baseName.vertexElement);
  23703. if (!vertexSource) {
  23704. vertexSource = baseName.vertexElement;
  23705. }
  23706. }
  23707. else {
  23708. vertexSource = baseName.vertex || baseName;
  23709. }
  23710. if (baseName.fragmentElement) {
  23711. fragmentSource = document.getElementById(baseName.fragmentElement);
  23712. if (!fragmentSource) {
  23713. fragmentSource = baseName.fragmentElement;
  23714. }
  23715. }
  23716. else {
  23717. fragmentSource = baseName.fragment || baseName;
  23718. }
  23719. this._loadVertexShader(vertexSource, function (vertexCode) {
  23720. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  23721. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  23722. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  23723. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  23724. });
  23725. });
  23726. });
  23727. });
  23728. }
  23729. // Properties
  23730. Effect.prototype.isReady = function () {
  23731. return this._isReady;
  23732. };
  23733. Effect.prototype.getProgram = function () {
  23734. return this._program;
  23735. };
  23736. Effect.prototype.getAttributesNames = function () {
  23737. return this._attributesNames;
  23738. };
  23739. Effect.prototype.getAttributeLocation = function (index) {
  23740. return this._attributes[index];
  23741. };
  23742. Effect.prototype.getAttributeLocationByName = function (name) {
  23743. var index = this._attributesNames.indexOf(name);
  23744. return this._attributes[index];
  23745. };
  23746. Effect.prototype.getAttributesCount = function () {
  23747. return this._attributes.length;
  23748. };
  23749. Effect.prototype.getUniformIndex = function (uniformName) {
  23750. return this._uniformsNames.indexOf(uniformName);
  23751. };
  23752. Effect.prototype.getUniform = function (uniformName) {
  23753. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  23754. };
  23755. Effect.prototype.getSamplers = function () {
  23756. return this._samplers;
  23757. };
  23758. Effect.prototype.getCompilationError = function () {
  23759. return this._compilationError;
  23760. };
  23761. // Methods
  23762. Effect.prototype._loadVertexShader = function (vertex, callback) {
  23763. // DOM element ?
  23764. if (vertex instanceof HTMLElement) {
  23765. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  23766. callback(vertexCode);
  23767. return;
  23768. }
  23769. // Is in local store ?
  23770. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  23771. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  23772. return;
  23773. }
  23774. var vertexShaderUrl;
  23775. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  23776. vertexShaderUrl = vertex;
  23777. }
  23778. else {
  23779. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  23780. }
  23781. // Vertex shader
  23782. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  23783. };
  23784. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  23785. // DOM element ?
  23786. if (fragment instanceof HTMLElement) {
  23787. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  23788. callback(fragmentCode);
  23789. return;
  23790. }
  23791. // Is in local store ?
  23792. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  23793. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  23794. return;
  23795. }
  23796. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  23797. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  23798. return;
  23799. }
  23800. var fragmentShaderUrl;
  23801. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  23802. fragmentShaderUrl = fragment;
  23803. }
  23804. else {
  23805. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  23806. }
  23807. // Fragment shader
  23808. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  23809. };
  23810. Effect.prototype._dumpShadersName = function () {
  23811. if (this.name.vertexElement) {
  23812. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  23813. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  23814. }
  23815. else if (this.name.vertex) {
  23816. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  23817. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  23818. }
  23819. else {
  23820. BABYLON.Tools.Error("Vertex shader:" + this.name);
  23821. BABYLON.Tools.Error("Fragment shader:" + this.name);
  23822. }
  23823. };
  23824. Effect.prototype._processIncludes = function (sourceCode, callback) {
  23825. var _this = this;
  23826. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  23827. var match = regex.exec(sourceCode);
  23828. var returnValue = new String(sourceCode);
  23829. while (match != null) {
  23830. var includeFile = match[1];
  23831. if (Effect.IncludesShadersStore[includeFile]) {
  23832. // Substitution
  23833. var includeContent = Effect.IncludesShadersStore[includeFile];
  23834. if (match[2]) {
  23835. var splits = match[3].split(",");
  23836. for (var index = 0; index < splits.length; index += 2) {
  23837. var source = new RegExp(splits[index], "g");
  23838. var dest = splits[index + 1];
  23839. includeContent = includeContent.replace(source, dest);
  23840. }
  23841. }
  23842. if (match[4]) {
  23843. var indexString = match[5];
  23844. if (indexString.indexOf("..") !== -1) {
  23845. var indexSplits = indexString.split("..");
  23846. var minIndex = parseInt(indexSplits[0]);
  23847. var maxIndex = parseInt(indexSplits[1]);
  23848. var sourceIncludeContent = includeContent.slice(0);
  23849. includeContent = "";
  23850. if (isNaN(maxIndex)) {
  23851. maxIndex = this._indexParameters[indexSplits[1]];
  23852. }
  23853. for (var i = minIndex; i <= maxIndex; i++) {
  23854. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  23855. }
  23856. }
  23857. else {
  23858. includeContent = includeContent.replace(/\{X\}/g, indexString);
  23859. }
  23860. }
  23861. // Replace
  23862. returnValue = returnValue.replace(match[0], includeContent);
  23863. }
  23864. else {
  23865. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  23866. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  23867. Effect.IncludesShadersStore[includeFile] = fileContent;
  23868. _this._processIncludes(returnValue, callback);
  23869. });
  23870. return;
  23871. }
  23872. match = regex.exec(sourceCode);
  23873. }
  23874. callback(returnValue);
  23875. };
  23876. Effect.prototype._processPrecision = function (source) {
  23877. if (source.indexOf("precision highp float") === -1) {
  23878. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23879. source = "precision mediump float;\n" + source;
  23880. }
  23881. else {
  23882. source = "precision highp float;\n" + source;
  23883. }
  23884. }
  23885. else {
  23886. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  23887. source = source.replace("precision highp float", "precision mediump float");
  23888. }
  23889. }
  23890. return source;
  23891. };
  23892. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  23893. try {
  23894. var engine = this._engine;
  23895. // Precision
  23896. vertexSourceCode = this._processPrecision(vertexSourceCode);
  23897. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  23898. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  23899. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  23900. this._attributes = engine.getAttributes(this._program, attributesNames);
  23901. var index;
  23902. for (index = 0; index < this._samplers.length; index++) {
  23903. var sampler = this.getUniform(this._samplers[index]);
  23904. if (sampler == null) {
  23905. this._samplers.splice(index, 1);
  23906. index--;
  23907. }
  23908. }
  23909. engine.bindSamplers(this);
  23910. this._isReady = true;
  23911. if (this.onCompiled) {
  23912. this.onCompiled(this);
  23913. }
  23914. }
  23915. catch (e) {
  23916. // Let's go through fallbacks then
  23917. if (fallbacks && fallbacks.isMoreFallbacks) {
  23918. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  23919. this._dumpShadersName();
  23920. defines = fallbacks.reduce(defines);
  23921. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  23922. }
  23923. else {
  23924. BABYLON.Tools.Error("Unable to compile effect: ");
  23925. this._dumpShadersName();
  23926. BABYLON.Tools.Error("Defines: " + defines);
  23927. BABYLON.Tools.Error("Error: " + e.message);
  23928. this._compilationError = e.message;
  23929. if (this.onError) {
  23930. this.onError(this, this._compilationError);
  23931. }
  23932. }
  23933. }
  23934. };
  23935. Object.defineProperty(Effect.prototype, "isSupported", {
  23936. get: function () {
  23937. return this._compilationError === "";
  23938. },
  23939. enumerable: true,
  23940. configurable: true
  23941. });
  23942. Effect.prototype._bindTexture = function (channel, texture) {
  23943. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  23944. };
  23945. Effect.prototype.setTexture = function (channel, texture) {
  23946. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  23947. };
  23948. Effect.prototype.setTextureArray = function (channel, textures) {
  23949. if (this._samplers.indexOf(channel + "Ex") === -1) {
  23950. var initialPos = this._samplers.indexOf(channel);
  23951. for (var index = 1; index < textures.length; index++) {
  23952. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  23953. }
  23954. }
  23955. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  23956. };
  23957. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  23958. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  23959. };
  23960. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  23961. var changed = false;
  23962. var cache = this._valueCache[uniformName];
  23963. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  23964. changed = true;
  23965. cache = new BABYLON.Matrix();
  23966. }
  23967. var tm = cache.m;
  23968. var om = matrix.m;
  23969. for (var index = 0; index < 16; index++) {
  23970. if (tm[index] !== om[index]) {
  23971. tm[index] = om[index];
  23972. changed = true;
  23973. }
  23974. }
  23975. this._valueCache[uniformName] = cache;
  23976. return changed;
  23977. };
  23978. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  23979. var cache = this._valueCache[uniformName];
  23980. if (!cache) {
  23981. cache = [x, y];
  23982. this._valueCache[uniformName] = cache;
  23983. return true;
  23984. }
  23985. var changed = false;
  23986. if (cache[0] !== x) {
  23987. cache[0] = x;
  23988. changed = true;
  23989. }
  23990. if (cache[1] !== y) {
  23991. cache[1] = y;
  23992. changed = true;
  23993. }
  23994. return changed;
  23995. };
  23996. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  23997. var cache = this._valueCache[uniformName];
  23998. if (!cache) {
  23999. cache = [x, y, z];
  24000. this._valueCache[uniformName] = cache;
  24001. return true;
  24002. }
  24003. var changed = false;
  24004. if (cache[0] !== x) {
  24005. cache[0] = x;
  24006. changed = true;
  24007. }
  24008. if (cache[1] !== y) {
  24009. cache[1] = y;
  24010. changed = true;
  24011. }
  24012. if (cache[2] !== z) {
  24013. cache[2] = z;
  24014. changed = true;
  24015. }
  24016. return changed;
  24017. };
  24018. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24019. var cache = this._valueCache[uniformName];
  24020. if (!cache) {
  24021. cache = [x, y, z, w];
  24022. this._valueCache[uniformName] = cache;
  24023. return true;
  24024. }
  24025. var changed = false;
  24026. if (cache[0] !== x) {
  24027. cache[0] = x;
  24028. changed = true;
  24029. }
  24030. if (cache[1] !== y) {
  24031. cache[1] = y;
  24032. changed = true;
  24033. }
  24034. if (cache[2] !== z) {
  24035. cache[2] = z;
  24036. changed = true;
  24037. }
  24038. if (cache[3] !== w) {
  24039. cache[3] = w;
  24040. changed = true;
  24041. }
  24042. return changed;
  24043. };
  24044. Effect.prototype.setIntArray = function (uniformName, array) {
  24045. this._valueCache[uniformName] = null;
  24046. this._engine.setIntArray(this.getUniform(uniformName), array);
  24047. return this;
  24048. };
  24049. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24050. this._valueCache[uniformName] = null;
  24051. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24052. return this;
  24053. };
  24054. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24055. this._valueCache[uniformName] = null;
  24056. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24057. return this;
  24058. };
  24059. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24060. this._valueCache[uniformName] = null;
  24061. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24062. return this;
  24063. };
  24064. Effect.prototype.setFloatArray = function (uniformName, array) {
  24065. this._valueCache[uniformName] = null;
  24066. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24067. return this;
  24068. };
  24069. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24070. this._valueCache[uniformName] = null;
  24071. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24072. return this;
  24073. };
  24074. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24075. this._valueCache[uniformName] = null;
  24076. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24077. return this;
  24078. };
  24079. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24080. this._valueCache[uniformName] = null;
  24081. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24082. return this;
  24083. };
  24084. Effect.prototype.setArray = function (uniformName, array) {
  24085. this._valueCache[uniformName] = null;
  24086. this._engine.setArray(this.getUniform(uniformName), array);
  24087. return this;
  24088. };
  24089. Effect.prototype.setArray2 = function (uniformName, array) {
  24090. this._valueCache[uniformName] = null;
  24091. this._engine.setArray2(this.getUniform(uniformName), array);
  24092. return this;
  24093. };
  24094. Effect.prototype.setArray3 = function (uniformName, array) {
  24095. this._valueCache[uniformName] = null;
  24096. this._engine.setArray3(this.getUniform(uniformName), array);
  24097. return this;
  24098. };
  24099. Effect.prototype.setArray4 = function (uniformName, array) {
  24100. this._valueCache[uniformName] = null;
  24101. this._engine.setArray4(this.getUniform(uniformName), array);
  24102. return this;
  24103. };
  24104. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24105. this._valueCache[uniformName] = null;
  24106. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24107. return this;
  24108. };
  24109. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24110. if (this._cacheMatrix(uniformName, matrix)) {
  24111. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24112. }
  24113. return this;
  24114. };
  24115. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24116. this._valueCache[uniformName] = null;
  24117. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24118. return this;
  24119. };
  24120. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24121. this._valueCache[uniformName] = null;
  24122. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24123. return this;
  24124. };
  24125. Effect.prototype.setFloat = function (uniformName, value) {
  24126. var cache = this._valueCache[uniformName];
  24127. if (cache !== undefined && cache === value)
  24128. return this;
  24129. this._valueCache[uniformName] = value;
  24130. this._engine.setFloat(this.getUniform(uniformName), value);
  24131. return this;
  24132. };
  24133. Effect.prototype.setBool = function (uniformName, bool) {
  24134. var cache = this._valueCache[uniformName];
  24135. if (cache !== undefined && cache === bool)
  24136. return this;
  24137. this._valueCache[uniformName] = bool;
  24138. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24139. return this;
  24140. };
  24141. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24142. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24143. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24144. }
  24145. return this;
  24146. };
  24147. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24148. if (this._cacheFloat2(uniformName, x, y)) {
  24149. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24150. }
  24151. return this;
  24152. };
  24153. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24154. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24155. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24156. }
  24157. return this;
  24158. };
  24159. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24160. if (this._cacheFloat3(uniformName, x, y, z)) {
  24161. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24162. }
  24163. return this;
  24164. };
  24165. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24166. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24167. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24168. }
  24169. return this;
  24170. };
  24171. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24172. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24173. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24174. }
  24175. return this;
  24176. };
  24177. Effect.prototype.setColor3 = function (uniformName, color3) {
  24178. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24179. this._engine.setColor3(this.getUniform(uniformName), color3);
  24180. }
  24181. return this;
  24182. };
  24183. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24184. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24185. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24186. }
  24187. return this;
  24188. };
  24189. // Statics
  24190. Effect.ShadersStore = {};
  24191. Effect.IncludesShadersStore = {};
  24192. return Effect;
  24193. }());
  24194. BABYLON.Effect = Effect;
  24195. })(BABYLON || (BABYLON = {}));
  24196. var BABYLON;
  24197. (function (BABYLON) {
  24198. var MaterialHelper = (function () {
  24199. function MaterialHelper() {
  24200. }
  24201. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24202. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24203. var lightIndex = 0;
  24204. var needNormals = false;
  24205. var needRebuild = false;
  24206. var needShadows = false;
  24207. for (var index = 0; index < scene.lights.length; index++) {
  24208. var light = scene.lights[index];
  24209. if (!light.isEnabled()) {
  24210. continue;
  24211. }
  24212. // Excluded check
  24213. if (light._excludedMeshesIds.length > 0) {
  24214. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24215. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24216. if (excludedMesh) {
  24217. light.excludedMeshes.push(excludedMesh);
  24218. }
  24219. }
  24220. light._excludedMeshesIds = [];
  24221. }
  24222. // Included check
  24223. if (light._includedOnlyMeshesIds.length > 0) {
  24224. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24225. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24226. if (includedOnlyMesh) {
  24227. light.includedOnlyMeshes.push(includedOnlyMesh);
  24228. }
  24229. }
  24230. light._includedOnlyMeshesIds = [];
  24231. }
  24232. if (!light.canAffectMesh(mesh)) {
  24233. continue;
  24234. }
  24235. needNormals = true;
  24236. if (defines["LIGHT" + lightIndex] === undefined) {
  24237. needRebuild = true;
  24238. }
  24239. defines["LIGHT" + lightIndex] = true;
  24240. var type;
  24241. if (light instanceof BABYLON.SpotLight) {
  24242. type = "SPOTLIGHT" + lightIndex;
  24243. }
  24244. else if (light instanceof BABYLON.HemisphericLight) {
  24245. type = "HEMILIGHT" + lightIndex;
  24246. }
  24247. else if (light instanceof BABYLON.PointLight) {
  24248. type = "POINTLIGHT" + lightIndex;
  24249. }
  24250. else {
  24251. type = "DIRLIGHT" + lightIndex;
  24252. }
  24253. if (defines[type] === undefined) {
  24254. needRebuild = true;
  24255. }
  24256. defines[type] = true;
  24257. // Specular
  24258. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  24259. defines["SPECULARTERM"] = true;
  24260. }
  24261. // Shadows
  24262. if (scene.shadowsEnabled) {
  24263. var shadowGenerator = light.getShadowGenerator();
  24264. if (mesh && mesh.receiveShadows && shadowGenerator) {
  24265. if (defines["SHADOW" + lightIndex] === undefined) {
  24266. needRebuild = true;
  24267. }
  24268. defines["SHADOW" + lightIndex] = true;
  24269. defines["SHADOWS"] = true;
  24270. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  24271. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  24272. needRebuild = true;
  24273. }
  24274. defines["SHADOWVSM" + lightIndex] = true;
  24275. }
  24276. if (shadowGenerator.usePoissonSampling) {
  24277. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  24278. needRebuild = true;
  24279. }
  24280. defines["SHADOWPCF" + lightIndex] = true;
  24281. }
  24282. needShadows = true;
  24283. }
  24284. }
  24285. lightIndex++;
  24286. if (lightIndex === maxSimultaneousLights)
  24287. break;
  24288. }
  24289. var caps = scene.getEngine().getCaps();
  24290. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  24291. if (defines["SHADOWFULLFLOAT"] === undefined) {
  24292. needRebuild = true;
  24293. }
  24294. defines["SHADOWFULLFLOAT"] = true;
  24295. }
  24296. if (needRebuild) {
  24297. defines.rebuild();
  24298. }
  24299. return needNormals;
  24300. };
  24301. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  24302. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24303. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24304. if (!defines["LIGHT" + lightIndex]) {
  24305. break;
  24306. }
  24307. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  24308. samplersList.push("shadowSampler" + lightIndex);
  24309. }
  24310. };
  24311. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24312. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24313. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24314. if (!defines["LIGHT" + lightIndex]) {
  24315. break;
  24316. }
  24317. if (lightIndex > 0) {
  24318. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24319. }
  24320. if (defines["SHADOW" + lightIndex]) {
  24321. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24322. }
  24323. if (defines["SHADOWPCF" + lightIndex]) {
  24324. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24325. }
  24326. if (defines["SHADOWVSM" + lightIndex]) {
  24327. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  24328. }
  24329. }
  24330. };
  24331. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24332. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24333. fallbacks.addCPUSkinningFallback(0, mesh);
  24334. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24335. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24336. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24337. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24338. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24339. }
  24340. }
  24341. };
  24342. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24343. if (defines["INSTANCES"]) {
  24344. attribs.push("world0");
  24345. attribs.push("world1");
  24346. attribs.push("world2");
  24347. attribs.push("world3");
  24348. }
  24349. };
  24350. // Bindings
  24351. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  24352. var shadowGenerator = light.getShadowGenerator();
  24353. if (mesh.receiveShadows && shadowGenerator) {
  24354. if (!light.needCube()) {
  24355. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  24356. }
  24357. else {
  24358. if (!depthValuesAlreadySet) {
  24359. depthValuesAlreadySet = true;
  24360. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  24361. }
  24362. }
  24363. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  24364. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  24365. }
  24366. return depthValuesAlreadySet;
  24367. };
  24368. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24369. if (light instanceof BABYLON.PointLight) {
  24370. // Point Light
  24371. light.transferToEffect(effect, "vLightData" + lightIndex);
  24372. }
  24373. else if (light instanceof BABYLON.DirectionalLight) {
  24374. // Directional Light
  24375. light.transferToEffect(effect, "vLightData" + lightIndex);
  24376. }
  24377. else if (light instanceof BABYLON.SpotLight) {
  24378. // Spot Light
  24379. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  24380. }
  24381. else if (light instanceof BABYLON.HemisphericLight) {
  24382. // Hemispheric Light
  24383. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  24384. }
  24385. };
  24386. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  24387. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24388. var lightIndex = 0;
  24389. var depthValuesAlreadySet = false;
  24390. for (var index = 0; index < scene.lights.length; index++) {
  24391. var light = scene.lights[index];
  24392. if (!light.isEnabled()) {
  24393. continue;
  24394. }
  24395. if (!light.canAffectMesh(mesh)) {
  24396. continue;
  24397. }
  24398. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24399. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  24400. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  24401. if (defines["SPECULARTERM"]) {
  24402. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  24403. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  24404. }
  24405. // Shadows
  24406. if (scene.shadowsEnabled) {
  24407. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  24408. }
  24409. lightIndex++;
  24410. if (lightIndex === maxSimultaneousLights)
  24411. break;
  24412. }
  24413. };
  24414. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24415. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24416. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24417. effect.setColor3("vFogColor", scene.fogColor);
  24418. }
  24419. };
  24420. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24421. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24422. effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  24423. }
  24424. };
  24425. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  24426. if (defines["LOGARITHMICDEPTH"]) {
  24427. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  24428. }
  24429. };
  24430. MaterialHelper.BindClipPlane = function (effect, scene) {
  24431. if (scene.clipPlane) {
  24432. var clipPlane = scene.clipPlane;
  24433. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  24434. }
  24435. };
  24436. return MaterialHelper;
  24437. }());
  24438. BABYLON.MaterialHelper = MaterialHelper;
  24439. })(BABYLON || (BABYLON = {}));
  24440. var BABYLON;
  24441. (function (BABYLON) {
  24442. var FresnelParameters = (function () {
  24443. function FresnelParameters() {
  24444. this.isEnabled = true;
  24445. this.leftColor = BABYLON.Color3.White();
  24446. this.rightColor = BABYLON.Color3.Black();
  24447. this.bias = 0;
  24448. this.power = 1;
  24449. }
  24450. FresnelParameters.prototype.clone = function () {
  24451. var newFresnelParameters = new FresnelParameters();
  24452. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  24453. return new FresnelParameters;
  24454. };
  24455. FresnelParameters.prototype.serialize = function () {
  24456. var serializationObject = {};
  24457. serializationObject.isEnabled = this.isEnabled;
  24458. serializationObject.leftColor = this.leftColor;
  24459. serializationObject.rightColor = this.rightColor;
  24460. serializationObject.bias = this.bias;
  24461. serializationObject.power = this.power;
  24462. return serializationObject;
  24463. };
  24464. FresnelParameters.Parse = function (parsedFresnelParameters) {
  24465. var fresnelParameters = new FresnelParameters();
  24466. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  24467. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  24468. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  24469. fresnelParameters.bias = parsedFresnelParameters.bias;
  24470. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  24471. return fresnelParameters;
  24472. };
  24473. return FresnelParameters;
  24474. }());
  24475. BABYLON.FresnelParameters = FresnelParameters;
  24476. })(BABYLON || (BABYLON = {}));
  24477. var BABYLON;
  24478. (function (BABYLON) {
  24479. var MaterialDefines = (function () {
  24480. function MaterialDefines() {
  24481. }
  24482. MaterialDefines.prototype.rebuild = function () {
  24483. if (this._keys) {
  24484. delete this._keys;
  24485. }
  24486. this._keys = Object.keys(this);
  24487. };
  24488. MaterialDefines.prototype.isEqual = function (other) {
  24489. if (this._keys.length !== other._keys.length) {
  24490. return false;
  24491. }
  24492. for (var index = 0; index < this._keys.length; index++) {
  24493. var prop = this._keys[index];
  24494. if (this[prop] !== other[prop]) {
  24495. return false;
  24496. }
  24497. }
  24498. return true;
  24499. };
  24500. MaterialDefines.prototype.cloneTo = function (other) {
  24501. if (this._keys.length !== other._keys.length) {
  24502. other._keys = this._keys.slice(0);
  24503. }
  24504. for (var index = 0; index < this._keys.length; index++) {
  24505. var prop = this._keys[index];
  24506. other[prop] = this[prop];
  24507. }
  24508. };
  24509. MaterialDefines.prototype.reset = function () {
  24510. for (var index = 0; index < this._keys.length; index++) {
  24511. var prop = this._keys[index];
  24512. if (typeof (this[prop]) === "number") {
  24513. this[prop] = 0;
  24514. }
  24515. else {
  24516. this[prop] = false;
  24517. }
  24518. }
  24519. };
  24520. MaterialDefines.prototype.toString = function () {
  24521. var result = "";
  24522. for (var index = 0; index < this._keys.length; index++) {
  24523. var prop = this._keys[index];
  24524. if (typeof (this[prop]) === "number") {
  24525. result += "#define " + prop + " " + this[prop] + "\n";
  24526. }
  24527. else if (this[prop]) {
  24528. result += "#define " + prop + "\n";
  24529. }
  24530. }
  24531. return result;
  24532. };
  24533. return MaterialDefines;
  24534. }());
  24535. BABYLON.MaterialDefines = MaterialDefines;
  24536. var Material = (function () {
  24537. function Material(name, scene, doNotAdd) {
  24538. this.name = name;
  24539. this.checkReadyOnEveryCall = false;
  24540. this.checkReadyOnlyOnce = false;
  24541. this.state = "";
  24542. this.alpha = 1.0;
  24543. this.backFaceCulling = true;
  24544. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  24545. /**
  24546. * An event triggered when the material is disposed.
  24547. * @type {BABYLON.Observable}
  24548. */
  24549. this.onDisposeObservable = new BABYLON.Observable();
  24550. /**
  24551. * An event triggered when the material is bound.
  24552. * @type {BABYLON.Observable}
  24553. */
  24554. this.onBindObservable = new BABYLON.Observable();
  24555. /**
  24556. * An event triggered when the material is unbound.
  24557. * @type {BABYLON.Observable}
  24558. */
  24559. this.onUnBindObservable = new BABYLON.Observable();
  24560. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  24561. this.disableDepthWrite = false;
  24562. this.fogEnabled = true;
  24563. this.pointSize = 1.0;
  24564. this.zOffset = 0;
  24565. this._wasPreviouslyReady = false;
  24566. this._fillMode = Material.TriangleFillMode;
  24567. this.id = name;
  24568. this._scene = scene;
  24569. if (!doNotAdd) {
  24570. scene.materials.push(this);
  24571. }
  24572. }
  24573. Object.defineProperty(Material, "TriangleFillMode", {
  24574. get: function () {
  24575. return Material._TriangleFillMode;
  24576. },
  24577. enumerable: true,
  24578. configurable: true
  24579. });
  24580. Object.defineProperty(Material, "WireFrameFillMode", {
  24581. get: function () {
  24582. return Material._WireFrameFillMode;
  24583. },
  24584. enumerable: true,
  24585. configurable: true
  24586. });
  24587. Object.defineProperty(Material, "PointFillMode", {
  24588. get: function () {
  24589. return Material._PointFillMode;
  24590. },
  24591. enumerable: true,
  24592. configurable: true
  24593. });
  24594. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  24595. get: function () {
  24596. return Material._ClockWiseSideOrientation;
  24597. },
  24598. enumerable: true,
  24599. configurable: true
  24600. });
  24601. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  24602. get: function () {
  24603. return Material._CounterClockWiseSideOrientation;
  24604. },
  24605. enumerable: true,
  24606. configurable: true
  24607. });
  24608. Object.defineProperty(Material.prototype, "onDispose", {
  24609. set: function (callback) {
  24610. if (this._onDisposeObserver) {
  24611. this.onDisposeObservable.remove(this._onDisposeObserver);
  24612. }
  24613. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24614. },
  24615. enumerable: true,
  24616. configurable: true
  24617. });
  24618. Object.defineProperty(Material.prototype, "onBind", {
  24619. set: function (callback) {
  24620. if (this._onBindObserver) {
  24621. this.onBindObservable.remove(this._onBindObserver);
  24622. }
  24623. this._onBindObserver = this.onBindObservable.add(callback);
  24624. },
  24625. enumerable: true,
  24626. configurable: true
  24627. });
  24628. Object.defineProperty(Material.prototype, "wireframe", {
  24629. get: function () {
  24630. return this._fillMode === Material.WireFrameFillMode;
  24631. },
  24632. set: function (value) {
  24633. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  24634. },
  24635. enumerable: true,
  24636. configurable: true
  24637. });
  24638. Object.defineProperty(Material.prototype, "pointsCloud", {
  24639. get: function () {
  24640. return this._fillMode === Material.PointFillMode;
  24641. },
  24642. set: function (value) {
  24643. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  24644. },
  24645. enumerable: true,
  24646. configurable: true
  24647. });
  24648. Object.defineProperty(Material.prototype, "fillMode", {
  24649. get: function () {
  24650. return this._fillMode;
  24651. },
  24652. set: function (value) {
  24653. this._fillMode = value;
  24654. },
  24655. enumerable: true,
  24656. configurable: true
  24657. });
  24658. /**
  24659. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  24660. * subclasses should override adding information pertainent to themselves
  24661. */
  24662. Material.prototype.toString = function (fullDetails) {
  24663. var ret = "Name: " + this.name;
  24664. if (fullDetails) {
  24665. }
  24666. return ret;
  24667. };
  24668. Object.defineProperty(Material.prototype, "isFrozen", {
  24669. get: function () {
  24670. return this.checkReadyOnlyOnce;
  24671. },
  24672. enumerable: true,
  24673. configurable: true
  24674. });
  24675. Material.prototype.freeze = function () {
  24676. this.checkReadyOnlyOnce = true;
  24677. };
  24678. Material.prototype.unfreeze = function () {
  24679. this.checkReadyOnlyOnce = false;
  24680. };
  24681. Material.prototype.isReady = function (mesh, useInstances) {
  24682. return true;
  24683. };
  24684. Material.prototype.getEffect = function () {
  24685. return this._effect;
  24686. };
  24687. Material.prototype.getScene = function () {
  24688. return this._scene;
  24689. };
  24690. Material.prototype.needAlphaBlending = function () {
  24691. return (this.alpha < 1.0);
  24692. };
  24693. Material.prototype.needAlphaTesting = function () {
  24694. return false;
  24695. };
  24696. Material.prototype.getAlphaTestTexture = function () {
  24697. return null;
  24698. };
  24699. Material.prototype.markDirty = function () {
  24700. this._wasPreviouslyReady = false;
  24701. };
  24702. Material.prototype._preBind = function () {
  24703. var engine = this._scene.getEngine();
  24704. engine.enableEffect(this._effect);
  24705. engine.setState(this.backFaceCulling, this.zOffset, false, this.sideOrientation === Material.ClockWiseSideOrientation);
  24706. };
  24707. Material.prototype.bind = function (world, mesh) {
  24708. this._scene._cachedMaterial = this;
  24709. this.onBindObservable.notifyObservers(mesh);
  24710. if (this.disableDepthWrite) {
  24711. var engine = this._scene.getEngine();
  24712. this._cachedDepthWriteState = engine.getDepthWrite();
  24713. engine.setDepthWrite(false);
  24714. }
  24715. };
  24716. Material.prototype.bindOnlyWorldMatrix = function (world) {
  24717. };
  24718. Material.prototype.unbind = function () {
  24719. this.onUnBindObservable.notifyObservers(this);
  24720. if (this.disableDepthWrite) {
  24721. var engine = this._scene.getEngine();
  24722. engine.setDepthWrite(this._cachedDepthWriteState);
  24723. }
  24724. };
  24725. Material.prototype.clone = function (name) {
  24726. return null;
  24727. };
  24728. Material.prototype.getBindedMeshes = function () {
  24729. var result = new Array();
  24730. for (var index = 0; index < this._scene.meshes.length; index++) {
  24731. var mesh = this._scene.meshes[index];
  24732. if (mesh.material === this) {
  24733. result.push(mesh);
  24734. }
  24735. }
  24736. return result;
  24737. };
  24738. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  24739. // Animations
  24740. this.getScene().stopAnimation(this);
  24741. // Remove from scene
  24742. var index = this._scene.materials.indexOf(this);
  24743. if (index >= 0) {
  24744. this._scene.materials.splice(index, 1);
  24745. }
  24746. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  24747. if (forceDisposeEffect && this._effect) {
  24748. this._scene.getEngine()._releaseEffect(this._effect);
  24749. this._effect = null;
  24750. }
  24751. // Remove from meshes
  24752. for (index = 0; index < this._scene.meshes.length; index++) {
  24753. var mesh = this._scene.meshes[index];
  24754. if (mesh.material === this) {
  24755. mesh.material = null;
  24756. }
  24757. }
  24758. // Callback
  24759. this.onDisposeObservable.notifyObservers(this);
  24760. this.onDisposeObservable.clear();
  24761. this.onBindObservable.clear();
  24762. };
  24763. Material.prototype.serialize = function () {
  24764. return BABYLON.SerializationHelper.Serialize(this);
  24765. };
  24766. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  24767. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  24768. multiMaterial.id = parsedMultiMaterial.id;
  24769. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  24770. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  24771. var subMatId = parsedMultiMaterial.materials[matIndex];
  24772. if (subMatId) {
  24773. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  24774. }
  24775. else {
  24776. multiMaterial.subMaterials.push(null);
  24777. }
  24778. }
  24779. return multiMaterial;
  24780. };
  24781. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  24782. if (!parsedMaterial.customType) {
  24783. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  24784. }
  24785. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  24786. return materialType.Parse(parsedMaterial, scene, rootUrl);
  24787. ;
  24788. };
  24789. Material._TriangleFillMode = 0;
  24790. Material._WireFrameFillMode = 1;
  24791. Material._PointFillMode = 2;
  24792. Material._ClockWiseSideOrientation = 0;
  24793. Material._CounterClockWiseSideOrientation = 1;
  24794. __decorate([
  24795. BABYLON.serialize()
  24796. ], Material.prototype, "id", void 0);
  24797. __decorate([
  24798. BABYLON.serialize()
  24799. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  24800. __decorate([
  24801. BABYLON.serialize()
  24802. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  24803. __decorate([
  24804. BABYLON.serialize()
  24805. ], Material.prototype, "state", void 0);
  24806. __decorate([
  24807. BABYLON.serialize()
  24808. ], Material.prototype, "alpha", void 0);
  24809. __decorate([
  24810. BABYLON.serialize()
  24811. ], Material.prototype, "backFaceCulling", void 0);
  24812. __decorate([
  24813. BABYLON.serialize()
  24814. ], Material.prototype, "sideOrientation", void 0);
  24815. __decorate([
  24816. BABYLON.serialize()
  24817. ], Material.prototype, "alphaMode", void 0);
  24818. __decorate([
  24819. BABYLON.serialize()
  24820. ], Material.prototype, "disableDepthWrite", void 0);
  24821. __decorate([
  24822. BABYLON.serialize()
  24823. ], Material.prototype, "fogEnabled", void 0);
  24824. __decorate([
  24825. BABYLON.serialize()
  24826. ], Material.prototype, "pointSize", void 0);
  24827. __decorate([
  24828. BABYLON.serialize()
  24829. ], Material.prototype, "zOffset", void 0);
  24830. __decorate([
  24831. BABYLON.serialize()
  24832. ], Material.prototype, "wireframe", null);
  24833. __decorate([
  24834. BABYLON.serialize()
  24835. ], Material.prototype, "pointsCloud", null);
  24836. __decorate([
  24837. BABYLON.serialize()
  24838. ], Material.prototype, "fillMode", null);
  24839. return Material;
  24840. }());
  24841. BABYLON.Material = Material;
  24842. })(BABYLON || (BABYLON = {}));
  24843. var BABYLON;
  24844. (function (BABYLON) {
  24845. var StandardMaterialDefines = (function (_super) {
  24846. __extends(StandardMaterialDefines, _super);
  24847. function StandardMaterialDefines() {
  24848. _super.call(this);
  24849. this.DIFFUSE = false;
  24850. this.AMBIENT = false;
  24851. this.OPACITY = false;
  24852. this.OPACITYRGB = false;
  24853. this.REFLECTION = false;
  24854. this.EMISSIVE = false;
  24855. this.SPECULAR = false;
  24856. this.BUMP = false;
  24857. this.PARALLAX = false;
  24858. this.PARALLAXOCCLUSION = false;
  24859. this.SPECULAROVERALPHA = false;
  24860. this.CLIPPLANE = false;
  24861. this.ALPHATEST = false;
  24862. this.ALPHAFROMDIFFUSE = false;
  24863. this.POINTSIZE = false;
  24864. this.FOG = false;
  24865. this.SPECULARTERM = false;
  24866. this.DIFFUSEFRESNEL = false;
  24867. this.OPACITYFRESNEL = false;
  24868. this.REFLECTIONFRESNEL = false;
  24869. this.REFRACTIONFRESNEL = false;
  24870. this.EMISSIVEFRESNEL = false;
  24871. this.FRESNEL = false;
  24872. this.NORMAL = false;
  24873. this.UV1 = false;
  24874. this.UV2 = false;
  24875. this.VERTEXCOLOR = false;
  24876. this.VERTEXALPHA = false;
  24877. this.NUM_BONE_INFLUENCERS = 0;
  24878. this.BonesPerMesh = 0;
  24879. this.INSTANCES = false;
  24880. this.GLOSSINESS = false;
  24881. this.ROUGHNESS = false;
  24882. this.EMISSIVEASILLUMINATION = false;
  24883. this.LINKEMISSIVEWITHDIFFUSE = false;
  24884. this.REFLECTIONFRESNELFROMSPECULAR = false;
  24885. this.LIGHTMAP = false;
  24886. this.USELIGHTMAPASSHADOWMAP = false;
  24887. this.REFLECTIONMAP_3D = false;
  24888. this.REFLECTIONMAP_SPHERICAL = false;
  24889. this.REFLECTIONMAP_PLANAR = false;
  24890. this.REFLECTIONMAP_CUBIC = false;
  24891. this.REFLECTIONMAP_PROJECTION = false;
  24892. this.REFLECTIONMAP_SKYBOX = false;
  24893. this.REFLECTIONMAP_EXPLICIT = false;
  24894. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  24895. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  24896. this.INVERTCUBICMAP = false;
  24897. this.LOGARITHMICDEPTH = false;
  24898. this.REFRACTION = false;
  24899. this.REFRACTIONMAP_3D = false;
  24900. this.REFLECTIONOVERALPHA = false;
  24901. this.INVERTNORMALMAPX = false;
  24902. this.INVERTNORMALMAPY = false;
  24903. this.SHADOWFULLFLOAT = false;
  24904. this.CAMERACOLORGRADING = false;
  24905. this.CAMERACOLORCURVES = false;
  24906. this.rebuild();
  24907. }
  24908. return StandardMaterialDefines;
  24909. }(BABYLON.MaterialDefines));
  24910. var StandardMaterial = (function (_super) {
  24911. __extends(StandardMaterial, _super);
  24912. function StandardMaterial(name, scene) {
  24913. var _this = this;
  24914. _super.call(this, name, scene);
  24915. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24916. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  24917. this.specularColor = new BABYLON.Color3(1, 1, 1);
  24918. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  24919. this.specularPower = 64;
  24920. this.useAlphaFromDiffuseTexture = false;
  24921. this.useEmissiveAsIllumination = false;
  24922. this.linkEmissiveWithDiffuse = false;
  24923. this.useReflectionFresnelFromSpecular = false;
  24924. this.useSpecularOverAlpha = false;
  24925. this.useReflectionOverAlpha = false;
  24926. this.disableLighting = false;
  24927. this.useParallax = false;
  24928. this.useParallaxOcclusion = false;
  24929. this.parallaxScaleBias = 0.05;
  24930. this.roughness = 0;
  24931. this.indexOfRefraction = 0.98;
  24932. this.invertRefractionY = true;
  24933. this.useLightmapAsShadowmap = false;
  24934. this.useGlossinessFromSpecularMapAlpha = false;
  24935. this.maxSimultaneousLights = 4;
  24936. /**
  24937. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  24938. */
  24939. this.invertNormalMapX = false;
  24940. /**
  24941. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  24942. */
  24943. this.invertNormalMapY = false;
  24944. /**
  24945. * Color Grading 2D Lookup Texture.
  24946. * This allows special effects like sepia, black and white to sixties rendering style.
  24947. */
  24948. this.cameraColorGradingTexture = null;
  24949. /**
  24950. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  24951. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  24952. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  24953. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  24954. */
  24955. this.cameraColorCurves = null;
  24956. this._renderTargets = new BABYLON.SmartArray(16);
  24957. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  24958. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  24959. this._defines = new StandardMaterialDefines();
  24960. this._cachedDefines = new StandardMaterialDefines();
  24961. this._cachedDefines.BonesPerMesh = -1;
  24962. this.getRenderTargetTextures = function () {
  24963. _this._renderTargets.reset();
  24964. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  24965. _this._renderTargets.push(_this.reflectionTexture);
  24966. }
  24967. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  24968. _this._renderTargets.push(_this.refractionTexture);
  24969. }
  24970. return _this._renderTargets;
  24971. };
  24972. }
  24973. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  24974. get: function () {
  24975. return this._useLogarithmicDepth;
  24976. },
  24977. set: function (value) {
  24978. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  24979. },
  24980. enumerable: true,
  24981. configurable: true
  24982. });
  24983. StandardMaterial.prototype.needAlphaBlending = function () {
  24984. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  24985. };
  24986. StandardMaterial.prototype.needAlphaTesting = function () {
  24987. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  24988. };
  24989. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  24990. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  24991. };
  24992. StandardMaterial.prototype.getAlphaTestTexture = function () {
  24993. return this.diffuseTexture;
  24994. };
  24995. // Methods
  24996. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  24997. if (!mesh) {
  24998. return true;
  24999. }
  25000. if (this._defines.INSTANCES !== useInstances) {
  25001. return false;
  25002. }
  25003. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  25004. return true;
  25005. }
  25006. return false;
  25007. };
  25008. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  25009. if (this.isFrozen) {
  25010. if (this._wasPreviouslyReady) {
  25011. return true;
  25012. }
  25013. }
  25014. var scene = this.getScene();
  25015. if (!this.checkReadyOnEveryCall) {
  25016. if (this._renderId === scene.getRenderId()) {
  25017. if (this._checkCache(scene, mesh, useInstances)) {
  25018. return true;
  25019. }
  25020. }
  25021. }
  25022. var engine = scene.getEngine();
  25023. var needNormals = false;
  25024. var needUVs = false;
  25025. this._defines.reset();
  25026. // Textures
  25027. if (scene.texturesEnabled) {
  25028. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25029. if (!this.diffuseTexture.isReady()) {
  25030. return false;
  25031. }
  25032. else {
  25033. needUVs = true;
  25034. this._defines.DIFFUSE = true;
  25035. }
  25036. }
  25037. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25038. if (!this.ambientTexture.isReady()) {
  25039. return false;
  25040. }
  25041. else {
  25042. needUVs = true;
  25043. this._defines.AMBIENT = true;
  25044. }
  25045. }
  25046. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25047. if (!this.opacityTexture.isReady()) {
  25048. return false;
  25049. }
  25050. else {
  25051. needUVs = true;
  25052. this._defines.OPACITY = true;
  25053. if (this.opacityTexture.getAlphaFromRGB) {
  25054. this._defines.OPACITYRGB = true;
  25055. }
  25056. }
  25057. }
  25058. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25059. if (!this.reflectionTexture.isReady()) {
  25060. return false;
  25061. }
  25062. else {
  25063. needNormals = true;
  25064. this._defines.REFLECTION = true;
  25065. if (this.roughness > 0) {
  25066. this._defines.ROUGHNESS = true;
  25067. }
  25068. if (this.useReflectionOverAlpha) {
  25069. this._defines.REFLECTIONOVERALPHA = true;
  25070. }
  25071. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  25072. this._defines.INVERTCUBICMAP = true;
  25073. }
  25074. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  25075. switch (this.reflectionTexture.coordinatesMode) {
  25076. case BABYLON.Texture.CUBIC_MODE:
  25077. case BABYLON.Texture.INVCUBIC_MODE:
  25078. this._defines.REFLECTIONMAP_CUBIC = true;
  25079. break;
  25080. case BABYLON.Texture.EXPLICIT_MODE:
  25081. this._defines.REFLECTIONMAP_EXPLICIT = true;
  25082. break;
  25083. case BABYLON.Texture.PLANAR_MODE:
  25084. this._defines.REFLECTIONMAP_PLANAR = true;
  25085. break;
  25086. case BABYLON.Texture.PROJECTION_MODE:
  25087. this._defines.REFLECTIONMAP_PROJECTION = true;
  25088. break;
  25089. case BABYLON.Texture.SKYBOX_MODE:
  25090. this._defines.REFLECTIONMAP_SKYBOX = true;
  25091. break;
  25092. case BABYLON.Texture.SPHERICAL_MODE:
  25093. this._defines.REFLECTIONMAP_SPHERICAL = true;
  25094. break;
  25095. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  25096. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  25097. break;
  25098. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  25099. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  25100. break;
  25101. }
  25102. }
  25103. }
  25104. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25105. if (!this.emissiveTexture.isReady()) {
  25106. return false;
  25107. }
  25108. else {
  25109. needUVs = true;
  25110. this._defines.EMISSIVE = true;
  25111. }
  25112. }
  25113. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25114. if (!this.lightmapTexture.isReady()) {
  25115. return false;
  25116. }
  25117. else {
  25118. needUVs = true;
  25119. this._defines.LIGHTMAP = true;
  25120. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  25121. }
  25122. }
  25123. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25124. if (!this.specularTexture.isReady()) {
  25125. return false;
  25126. }
  25127. else {
  25128. needUVs = true;
  25129. this._defines.SPECULAR = true;
  25130. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25131. }
  25132. }
  25133. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25134. if (!this.bumpTexture.isReady()) {
  25135. return false;
  25136. }
  25137. else {
  25138. needUVs = true;
  25139. this._defines.BUMP = true;
  25140. if (this.useParallax) {
  25141. this._defines.PARALLAX = true;
  25142. if (this.useParallaxOcclusion) {
  25143. this._defines.PARALLAXOCCLUSION = true;
  25144. }
  25145. }
  25146. if (this.invertNormalMapX) {
  25147. this._defines.INVERTNORMALMAPX = true;
  25148. }
  25149. if (this.invertNormalMapY) {
  25150. this._defines.INVERTNORMALMAPY = true;
  25151. }
  25152. }
  25153. }
  25154. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25155. if (!this.refractionTexture.isReady()) {
  25156. return false;
  25157. }
  25158. else {
  25159. needUVs = true;
  25160. this._defines.REFRACTION = true;
  25161. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25162. }
  25163. }
  25164. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25165. if (!this.cameraColorGradingTexture.isReady()) {
  25166. return false;
  25167. }
  25168. else {
  25169. this._defines.CAMERACOLORGRADING = true;
  25170. }
  25171. }
  25172. }
  25173. // Effect
  25174. if (scene.clipPlane) {
  25175. this._defines.CLIPPLANE = true;
  25176. }
  25177. if (engine.getAlphaTesting()) {
  25178. this._defines.ALPHATEST = true;
  25179. }
  25180. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25181. this._defines.ALPHAFROMDIFFUSE = true;
  25182. }
  25183. if (this.useEmissiveAsIllumination) {
  25184. this._defines.EMISSIVEASILLUMINATION = true;
  25185. }
  25186. if (this.linkEmissiveWithDiffuse) {
  25187. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25188. }
  25189. if (this.useLogarithmicDepth) {
  25190. this._defines.LOGARITHMICDEPTH = true;
  25191. }
  25192. if (this.cameraColorCurves) {
  25193. this._defines.CAMERACOLORCURVES = true;
  25194. }
  25195. // Point size
  25196. if (this.pointsCloud || scene.forcePointsCloud) {
  25197. this._defines.POINTSIZE = true;
  25198. }
  25199. // Fog
  25200. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25201. this._defines.FOG = true;
  25202. }
  25203. if (scene.lightsEnabled && !this.disableLighting) {
  25204. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25205. }
  25206. if (StandardMaterial.FresnelEnabled) {
  25207. // Fresnel
  25208. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  25209. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  25210. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  25211. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  25212. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25213. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25214. this._defines.DIFFUSEFRESNEL = true;
  25215. }
  25216. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25217. this._defines.OPACITYFRESNEL = true;
  25218. }
  25219. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25220. this._defines.REFLECTIONFRESNEL = true;
  25221. if (this.useReflectionFresnelFromSpecular) {
  25222. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  25223. }
  25224. }
  25225. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25226. this._defines.REFRACTIONFRESNEL = true;
  25227. }
  25228. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25229. this._defines.EMISSIVEFRESNEL = true;
  25230. }
  25231. needNormals = true;
  25232. this._defines.FRESNEL = true;
  25233. }
  25234. }
  25235. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  25236. this._defines.SPECULAROVERALPHA = true;
  25237. }
  25238. // Attribs
  25239. if (mesh) {
  25240. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  25241. this._defines.NORMAL = true;
  25242. }
  25243. if (needUVs) {
  25244. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25245. this._defines.UV1 = true;
  25246. }
  25247. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25248. this._defines.UV2 = true;
  25249. }
  25250. }
  25251. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  25252. this._defines.VERTEXCOLOR = true;
  25253. if (mesh.hasVertexAlpha) {
  25254. this._defines.VERTEXALPHA = true;
  25255. }
  25256. }
  25257. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  25258. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  25259. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  25260. }
  25261. // Instances
  25262. if (useInstances) {
  25263. this._defines.INSTANCES = true;
  25264. }
  25265. }
  25266. // Get correct effect
  25267. if (!this._defines.isEqual(this._cachedDefines)) {
  25268. this._defines.cloneTo(this._cachedDefines);
  25269. scene.resetCachedMaterial();
  25270. // Fallbacks
  25271. var fallbacks = new BABYLON.EffectFallbacks();
  25272. if (this._defines.REFLECTION) {
  25273. fallbacks.addFallback(0, "REFLECTION");
  25274. }
  25275. if (this._defines.SPECULAR) {
  25276. fallbacks.addFallback(0, "SPECULAR");
  25277. }
  25278. if (this._defines.BUMP) {
  25279. fallbacks.addFallback(0, "BUMP");
  25280. }
  25281. if (this._defines.PARALLAX) {
  25282. fallbacks.addFallback(1, "PARALLAX");
  25283. }
  25284. if (this._defines.PARALLAXOCCLUSION) {
  25285. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  25286. }
  25287. if (this._defines.SPECULAROVERALPHA) {
  25288. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  25289. }
  25290. if (this._defines.FOG) {
  25291. fallbacks.addFallback(1, "FOG");
  25292. }
  25293. if (this._defines.POINTSIZE) {
  25294. fallbacks.addFallback(0, "POINTSIZE");
  25295. }
  25296. if (this._defines.LOGARITHMICDEPTH) {
  25297. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  25298. }
  25299. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  25300. if (this._defines.SPECULARTERM) {
  25301. fallbacks.addFallback(0, "SPECULARTERM");
  25302. }
  25303. if (this._defines.DIFFUSEFRESNEL) {
  25304. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  25305. }
  25306. if (this._defines.OPACITYFRESNEL) {
  25307. fallbacks.addFallback(2, "OPACITYFRESNEL");
  25308. }
  25309. if (this._defines.REFLECTIONFRESNEL) {
  25310. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  25311. }
  25312. if (this._defines.EMISSIVEFRESNEL) {
  25313. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  25314. }
  25315. if (this._defines.FRESNEL) {
  25316. fallbacks.addFallback(4, "FRESNEL");
  25317. }
  25318. //Attributes
  25319. var attribs = [BABYLON.VertexBuffer.PositionKind];
  25320. if (this._defines.NORMAL) {
  25321. attribs.push(BABYLON.VertexBuffer.NormalKind);
  25322. }
  25323. if (this._defines.UV1) {
  25324. attribs.push(BABYLON.VertexBuffer.UVKind);
  25325. }
  25326. if (this._defines.UV2) {
  25327. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25328. }
  25329. if (this._defines.VERTEXCOLOR) {
  25330. attribs.push(BABYLON.VertexBuffer.ColorKind);
  25331. }
  25332. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  25333. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  25334. var shaderName = "default";
  25335. var join = this._defines.toString();
  25336. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  25337. "vFogInfos", "vFogColor", "pointSize",
  25338. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  25339. "mBones",
  25340. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  25341. "depthValues",
  25342. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  25343. "logarithmicDepthConstant"
  25344. ];
  25345. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  25346. if (this._defines.CAMERACOLORCURVES) {
  25347. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  25348. }
  25349. if (this._defines.CAMERACOLORGRADING) {
  25350. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  25351. }
  25352. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  25353. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  25354. }
  25355. if (!this._effect.isReady()) {
  25356. return false;
  25357. }
  25358. this._renderId = scene.getRenderId();
  25359. this._wasPreviouslyReady = true;
  25360. if (mesh) {
  25361. if (!mesh._materialDefines) {
  25362. mesh._materialDefines = new StandardMaterialDefines();
  25363. }
  25364. this._defines.cloneTo(mesh._materialDefines);
  25365. }
  25366. return true;
  25367. };
  25368. StandardMaterial.prototype.unbind = function () {
  25369. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  25370. this._effect.setTexture("reflection2DSampler", null);
  25371. }
  25372. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  25373. this._effect.setTexture("refraction2DSampler", null);
  25374. }
  25375. _super.prototype.unbind.call(this);
  25376. };
  25377. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  25378. this._effect.setMatrix("world", world);
  25379. };
  25380. StandardMaterial.prototype.bind = function (world, mesh) {
  25381. var scene = this.getScene();
  25382. // Matrices
  25383. this.bindOnlyWorldMatrix(world);
  25384. // Bones
  25385. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  25386. if (scene.getCachedMaterial() !== this) {
  25387. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25388. if (StandardMaterial.FresnelEnabled) {
  25389. // Fresnel
  25390. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25391. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  25392. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  25393. }
  25394. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  25395. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  25396. }
  25397. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25398. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  25399. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  25400. }
  25401. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  25402. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  25403. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  25404. }
  25405. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  25406. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  25407. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  25408. }
  25409. }
  25410. // Textures
  25411. if (scene.texturesEnabled) {
  25412. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25413. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  25414. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  25415. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  25416. }
  25417. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25418. this._effect.setTexture("ambientSampler", this.ambientTexture);
  25419. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  25420. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  25421. }
  25422. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25423. this._effect.setTexture("opacitySampler", this.opacityTexture);
  25424. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  25425. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  25426. }
  25427. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25428. if (this.reflectionTexture.isCube) {
  25429. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  25430. }
  25431. else {
  25432. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  25433. }
  25434. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  25435. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  25436. }
  25437. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25438. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  25439. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  25440. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  25441. }
  25442. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25443. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  25444. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  25445. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  25446. }
  25447. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25448. this._effect.setTexture("specularSampler", this.specularTexture);
  25449. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  25450. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  25451. }
  25452. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  25453. this._effect.setTexture("bumpSampler", this.bumpTexture);
  25454. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  25455. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  25456. }
  25457. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25458. var depth = 1.0;
  25459. if (this.refractionTexture.isCube) {
  25460. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  25461. }
  25462. else {
  25463. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  25464. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  25465. if (this.refractionTexture.depth) {
  25466. depth = this.refractionTexture.depth;
  25467. }
  25468. }
  25469. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  25470. }
  25471. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25472. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  25473. }
  25474. }
  25475. // Clip plane
  25476. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  25477. // Point size
  25478. if (this.pointsCloud) {
  25479. this._effect.setFloat("pointSize", this.pointSize);
  25480. }
  25481. // Colors
  25482. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  25483. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  25484. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  25485. if (this._defines.SPECULARTERM) {
  25486. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  25487. }
  25488. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  25489. }
  25490. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  25491. // Diffuse
  25492. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  25493. // Lights
  25494. if (scene.lightsEnabled && !this.disableLighting) {
  25495. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  25496. }
  25497. // View
  25498. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  25499. this._effect.setMatrix("view", scene.getViewMatrix());
  25500. }
  25501. // Fog
  25502. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  25503. // Log. depth
  25504. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  25505. // Color Curves
  25506. if (this.cameraColorCurves) {
  25507. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  25508. }
  25509. }
  25510. _super.prototype.bind.call(this, world, mesh);
  25511. };
  25512. StandardMaterial.prototype.getAnimatables = function () {
  25513. var results = [];
  25514. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  25515. results.push(this.diffuseTexture);
  25516. }
  25517. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  25518. results.push(this.ambientTexture);
  25519. }
  25520. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  25521. results.push(this.opacityTexture);
  25522. }
  25523. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  25524. results.push(this.reflectionTexture);
  25525. }
  25526. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  25527. results.push(this.emissiveTexture);
  25528. }
  25529. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  25530. results.push(this.specularTexture);
  25531. }
  25532. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  25533. results.push(this.bumpTexture);
  25534. }
  25535. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  25536. results.push(this.lightmapTexture);
  25537. }
  25538. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  25539. results.push(this.refractionTexture);
  25540. }
  25541. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  25542. results.push(this.cameraColorGradingTexture);
  25543. }
  25544. return results;
  25545. };
  25546. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25547. if (forceDisposeTextures) {
  25548. if (this.diffuseTexture) {
  25549. this.diffuseTexture.dispose();
  25550. }
  25551. if (this.ambientTexture) {
  25552. this.ambientTexture.dispose();
  25553. }
  25554. if (this.opacityTexture) {
  25555. this.opacityTexture.dispose();
  25556. }
  25557. if (this.reflectionTexture) {
  25558. this.reflectionTexture.dispose();
  25559. }
  25560. if (this.emissiveTexture) {
  25561. this.emissiveTexture.dispose();
  25562. }
  25563. if (this.specularTexture) {
  25564. this.specularTexture.dispose();
  25565. }
  25566. if (this.bumpTexture) {
  25567. this.bumpTexture.dispose();
  25568. }
  25569. if (this.lightmapTexture) {
  25570. this.lightmapTexture.dispose();
  25571. }
  25572. if (this.refractionTexture) {
  25573. this.refractionTexture.dispose();
  25574. }
  25575. if (this.cameraColorGradingTexture) {
  25576. this.cameraColorGradingTexture.dispose();
  25577. }
  25578. }
  25579. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  25580. };
  25581. StandardMaterial.prototype.clone = function (name) {
  25582. var _this = this;
  25583. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  25584. };
  25585. StandardMaterial.prototype.serialize = function () {
  25586. return BABYLON.SerializationHelper.Serialize(this);
  25587. };
  25588. // Statics
  25589. StandardMaterial.Parse = function (source, scene, rootUrl) {
  25590. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  25591. };
  25592. // Flags used to enable or disable a type of texture for all Standard Materials
  25593. StandardMaterial.DiffuseTextureEnabled = true;
  25594. StandardMaterial.AmbientTextureEnabled = true;
  25595. StandardMaterial.OpacityTextureEnabled = true;
  25596. StandardMaterial.ReflectionTextureEnabled = true;
  25597. StandardMaterial.EmissiveTextureEnabled = true;
  25598. StandardMaterial.SpecularTextureEnabled = true;
  25599. StandardMaterial.BumpTextureEnabled = true;
  25600. StandardMaterial.FresnelEnabled = true;
  25601. StandardMaterial.LightmapTextureEnabled = true;
  25602. StandardMaterial.RefractionTextureEnabled = true;
  25603. StandardMaterial.ColorGradingTextureEnabled = true;
  25604. __decorate([
  25605. BABYLON.serializeAsTexture()
  25606. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  25607. __decorate([
  25608. BABYLON.serializeAsTexture()
  25609. ], StandardMaterial.prototype, "ambientTexture", void 0);
  25610. __decorate([
  25611. BABYLON.serializeAsTexture()
  25612. ], StandardMaterial.prototype, "opacityTexture", void 0);
  25613. __decorate([
  25614. BABYLON.serializeAsTexture()
  25615. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  25616. __decorate([
  25617. BABYLON.serializeAsTexture()
  25618. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  25619. __decorate([
  25620. BABYLON.serializeAsTexture()
  25621. ], StandardMaterial.prototype, "specularTexture", void 0);
  25622. __decorate([
  25623. BABYLON.serializeAsTexture()
  25624. ], StandardMaterial.prototype, "bumpTexture", void 0);
  25625. __decorate([
  25626. BABYLON.serializeAsTexture()
  25627. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  25628. __decorate([
  25629. BABYLON.serializeAsTexture()
  25630. ], StandardMaterial.prototype, "refractionTexture", void 0);
  25631. __decorate([
  25632. BABYLON.serializeAsColor3("ambient")
  25633. ], StandardMaterial.prototype, "ambientColor", void 0);
  25634. __decorate([
  25635. BABYLON.serializeAsColor3("diffuse")
  25636. ], StandardMaterial.prototype, "diffuseColor", void 0);
  25637. __decorate([
  25638. BABYLON.serializeAsColor3("specular")
  25639. ], StandardMaterial.prototype, "specularColor", void 0);
  25640. __decorate([
  25641. BABYLON.serializeAsColor3("emissive")
  25642. ], StandardMaterial.prototype, "emissiveColor", void 0);
  25643. __decorate([
  25644. BABYLON.serialize()
  25645. ], StandardMaterial.prototype, "specularPower", void 0);
  25646. __decorate([
  25647. BABYLON.serialize()
  25648. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  25649. __decorate([
  25650. BABYLON.serialize()
  25651. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  25652. __decorate([
  25653. BABYLON.serialize()
  25654. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  25655. __decorate([
  25656. BABYLON.serialize()
  25657. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  25658. __decorate([
  25659. BABYLON.serialize()
  25660. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  25661. __decorate([
  25662. BABYLON.serialize()
  25663. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  25664. __decorate([
  25665. BABYLON.serialize()
  25666. ], StandardMaterial.prototype, "disableLighting", void 0);
  25667. __decorate([
  25668. BABYLON.serialize()
  25669. ], StandardMaterial.prototype, "useParallax", void 0);
  25670. __decorate([
  25671. BABYLON.serialize()
  25672. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  25673. __decorate([
  25674. BABYLON.serialize()
  25675. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  25676. __decorate([
  25677. BABYLON.serialize()
  25678. ], StandardMaterial.prototype, "roughness", void 0);
  25679. __decorate([
  25680. BABYLON.serialize()
  25681. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  25682. __decorate([
  25683. BABYLON.serialize()
  25684. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  25685. __decorate([
  25686. BABYLON.serialize()
  25687. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  25688. __decorate([
  25689. BABYLON.serializeAsFresnelParameters()
  25690. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  25691. __decorate([
  25692. BABYLON.serializeAsFresnelParameters()
  25693. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  25694. __decorate([
  25695. BABYLON.serializeAsFresnelParameters()
  25696. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  25697. __decorate([
  25698. BABYLON.serializeAsFresnelParameters()
  25699. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  25700. __decorate([
  25701. BABYLON.serializeAsFresnelParameters()
  25702. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  25703. __decorate([
  25704. BABYLON.serialize()
  25705. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  25706. __decorate([
  25707. BABYLON.serialize()
  25708. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  25709. __decorate([
  25710. BABYLON.serialize()
  25711. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  25712. __decorate([
  25713. BABYLON.serialize()
  25714. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  25715. __decorate([
  25716. BABYLON.serializeAsTexture()
  25717. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  25718. __decorate([
  25719. BABYLON.serializeAsColorCurves()
  25720. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  25721. __decorate([
  25722. BABYLON.serialize()
  25723. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  25724. return StandardMaterial;
  25725. }(BABYLON.Material));
  25726. BABYLON.StandardMaterial = StandardMaterial;
  25727. })(BABYLON || (BABYLON = {}));
  25728. var BABYLON;
  25729. (function (BABYLON) {
  25730. var MultiMaterial = (function (_super) {
  25731. __extends(MultiMaterial, _super);
  25732. function MultiMaterial(name, scene) {
  25733. _super.call(this, name, scene, true);
  25734. this.subMaterials = new Array();
  25735. scene.multiMaterials.push(this);
  25736. }
  25737. // Properties
  25738. MultiMaterial.prototype.getSubMaterial = function (index) {
  25739. if (index < 0 || index >= this.subMaterials.length) {
  25740. return this.getScene().defaultMaterial;
  25741. }
  25742. return this.subMaterials[index];
  25743. };
  25744. // Methods
  25745. MultiMaterial.prototype.isReady = function (mesh) {
  25746. for (var index = 0; index < this.subMaterials.length; index++) {
  25747. var subMaterial = this.subMaterials[index];
  25748. if (subMaterial) {
  25749. if (!this.subMaterials[index].isReady(mesh)) {
  25750. return false;
  25751. }
  25752. }
  25753. }
  25754. return true;
  25755. };
  25756. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  25757. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  25758. for (var index = 0; index < this.subMaterials.length; index++) {
  25759. var subMaterial = null;
  25760. if (cloneChildren) {
  25761. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  25762. }
  25763. else {
  25764. subMaterial = this.subMaterials[index];
  25765. }
  25766. newMultiMaterial.subMaterials.push(subMaterial);
  25767. }
  25768. return newMultiMaterial;
  25769. };
  25770. MultiMaterial.prototype.serialize = function () {
  25771. var serializationObject = {};
  25772. serializationObject.name = this.name;
  25773. serializationObject.id = this.id;
  25774. serializationObject.tags = BABYLON.Tags.GetTags(this);
  25775. serializationObject.materials = [];
  25776. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  25777. var subMat = this.subMaterials[matIndex];
  25778. if (subMat) {
  25779. serializationObject.materials.push(subMat.id);
  25780. }
  25781. else {
  25782. serializationObject.materials.push(null);
  25783. }
  25784. }
  25785. return serializationObject;
  25786. };
  25787. return MultiMaterial;
  25788. }(BABYLON.Material));
  25789. BABYLON.MultiMaterial = MultiMaterial;
  25790. })(BABYLON || (BABYLON = {}));
  25791. var BABYLON;
  25792. (function (BABYLON) {
  25793. var SceneLoader = (function () {
  25794. function SceneLoader() {
  25795. }
  25796. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  25797. get: function () {
  25798. return 0;
  25799. },
  25800. enumerable: true,
  25801. configurable: true
  25802. });
  25803. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  25804. get: function () {
  25805. return 1;
  25806. },
  25807. enumerable: true,
  25808. configurable: true
  25809. });
  25810. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  25811. get: function () {
  25812. return 2;
  25813. },
  25814. enumerable: true,
  25815. configurable: true
  25816. });
  25817. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  25818. get: function () {
  25819. return 3;
  25820. },
  25821. enumerable: true,
  25822. configurable: true
  25823. });
  25824. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  25825. get: function () {
  25826. return SceneLoader._ForceFullSceneLoadingForIncremental;
  25827. },
  25828. set: function (value) {
  25829. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  25830. },
  25831. enumerable: true,
  25832. configurable: true
  25833. });
  25834. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  25835. get: function () {
  25836. return SceneLoader._ShowLoadingScreen;
  25837. },
  25838. set: function (value) {
  25839. SceneLoader._ShowLoadingScreen = value;
  25840. },
  25841. enumerable: true,
  25842. configurable: true
  25843. });
  25844. Object.defineProperty(SceneLoader, "loggingLevel", {
  25845. get: function () {
  25846. return SceneLoader._loggingLevel;
  25847. },
  25848. set: function (value) {
  25849. SceneLoader._loggingLevel = value;
  25850. },
  25851. enumerable: true,
  25852. configurable: true
  25853. });
  25854. SceneLoader._getPluginForFilename = function (sceneFilename) {
  25855. var dotPosition = sceneFilename.lastIndexOf(".");
  25856. var queryStringPosition = sceneFilename.indexOf("?");
  25857. if (queryStringPosition === -1) {
  25858. queryStringPosition = sceneFilename.length;
  25859. }
  25860. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  25861. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25862. var plugin = this._registeredPlugins[index];
  25863. if (plugin.extensions.indexOf(extension) !== -1) {
  25864. return plugin;
  25865. }
  25866. }
  25867. return this._registeredPlugins[0];
  25868. };
  25869. // Public functions
  25870. SceneLoader.GetPluginForExtension = function (extension) {
  25871. for (var index = 0; index < this._registeredPlugins.length; index++) {
  25872. var plugin = this._registeredPlugins[index];
  25873. if (plugin.extensions.indexOf(extension) !== -1) {
  25874. return plugin;
  25875. }
  25876. }
  25877. return null;
  25878. };
  25879. SceneLoader.RegisterPlugin = function (plugin) {
  25880. plugin.extensions = plugin.extensions.toLowerCase();
  25881. SceneLoader._registeredPlugins.push(plugin);
  25882. };
  25883. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25884. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25885. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25886. return;
  25887. }
  25888. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25889. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25890. return;
  25891. }
  25892. var loadingToken = {};
  25893. scene._addPendingData(loadingToken);
  25894. var manifestChecked = function (success) {
  25895. scene.database = database;
  25896. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  25897. var importMeshFromData = function (data) {
  25898. var meshes = [];
  25899. var particleSystems = [];
  25900. var skeletons = [];
  25901. try {
  25902. if (plugin.importMesh) {
  25903. var syncedPlugin = plugin;
  25904. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  25905. if (onerror) {
  25906. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25907. }
  25908. scene._removePendingData(loadingToken);
  25909. return;
  25910. }
  25911. if (onsuccess) {
  25912. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25913. onsuccess(meshes, particleSystems, skeletons);
  25914. scene._removePendingData(loadingToken);
  25915. }
  25916. }
  25917. else {
  25918. var asyncedPlugin = plugin;
  25919. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  25920. if (onsuccess) {
  25921. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  25922. onsuccess(meshes, particleSystems, skeletons);
  25923. scene._removePendingData(loadingToken);
  25924. }
  25925. }, function () {
  25926. if (onerror) {
  25927. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  25928. }
  25929. scene._removePendingData(loadingToken);
  25930. });
  25931. }
  25932. }
  25933. catch (e) {
  25934. if (onerror) {
  25935. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  25936. }
  25937. scene._removePendingData(loadingToken);
  25938. }
  25939. };
  25940. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  25941. // Direct load
  25942. importMeshFromData(sceneFilename.substr(5));
  25943. return;
  25944. }
  25945. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  25946. importMeshFromData(data);
  25947. }, progressCallBack, database);
  25948. };
  25949. if (scene.getEngine().enableOfflineSupport && !(sceneFilename.substr && sceneFilename.substr(0, 5) === "data:")) {
  25950. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  25951. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  25952. }
  25953. else {
  25954. // If the scene is a data stream or offline support is not enabled, it's a direct load
  25955. manifestChecked(true);
  25956. }
  25957. };
  25958. /**
  25959. * Load a scene
  25960. * @param rootUrl a string that defines the root url for scene and resources
  25961. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25962. * @param engine is the instance of BABYLON.Engine to use to create the scene
  25963. */
  25964. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  25965. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  25966. };
  25967. /**
  25968. * Append a scene
  25969. * @param rootUrl a string that defines the root url for scene and resources
  25970. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  25971. * @param scene is the instance of BABYLON.Scene to append to
  25972. */
  25973. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  25974. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  25975. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  25976. return;
  25977. }
  25978. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  25979. var database;
  25980. var loadingToken = {};
  25981. scene._addPendingData(loadingToken);
  25982. if (SceneLoader.ShowLoadingScreen) {
  25983. scene.getEngine().displayLoadingUI();
  25984. }
  25985. var loadSceneFromData = function (data) {
  25986. scene.database = database;
  25987. if (plugin.load) {
  25988. var syncedPlugin = plugin;
  25989. if (!syncedPlugin.load(scene, data, rootUrl)) {
  25990. if (onerror) {
  25991. onerror(scene);
  25992. }
  25993. scene._removePendingData(loadingToken);
  25994. scene.getEngine().hideLoadingUI();
  25995. return;
  25996. }
  25997. if (onsuccess) {
  25998. onsuccess(scene);
  25999. }
  26000. scene._removePendingData(loadingToken);
  26001. }
  26002. else {
  26003. var asyncedPlugin = plugin;
  26004. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  26005. if (onsuccess) {
  26006. onsuccess(scene);
  26007. }
  26008. }, function () {
  26009. if (onerror) {
  26010. onerror(scene);
  26011. }
  26012. scene._removePendingData(loadingToken);
  26013. scene.getEngine().hideLoadingUI();
  26014. });
  26015. }
  26016. if (SceneLoader.ShowLoadingScreen) {
  26017. scene.executeWhenReady(function () {
  26018. scene.getEngine().hideLoadingUI();
  26019. });
  26020. }
  26021. };
  26022. var manifestChecked = function (success) {
  26023. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  26024. };
  26025. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26026. // Direct load
  26027. loadSceneFromData(sceneFilename.substr(5));
  26028. return;
  26029. }
  26030. if (rootUrl.indexOf("file:") === -1) {
  26031. if (scene.getEngine().enableOfflineSupport) {
  26032. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26033. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26034. }
  26035. else {
  26036. manifestChecked(true);
  26037. }
  26038. }
  26039. else {
  26040. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  26041. }
  26042. };
  26043. // Flags
  26044. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  26045. SceneLoader._ShowLoadingScreen = true;
  26046. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  26047. // Members
  26048. SceneLoader._registeredPlugins = new Array();
  26049. return SceneLoader;
  26050. }());
  26051. BABYLON.SceneLoader = SceneLoader;
  26052. ;
  26053. })(BABYLON || (BABYLON = {}));
  26054. var BABYLON;
  26055. (function (BABYLON) {
  26056. var Internals;
  26057. (function (Internals) {
  26058. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  26059. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26060. var parsedMaterial = parsedData.materials[index];
  26061. if (parsedMaterial.id === id) {
  26062. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26063. }
  26064. }
  26065. return null;
  26066. };
  26067. var isDescendantOf = function (mesh, names, hierarchyIds) {
  26068. names = (names instanceof Array) ? names : [names];
  26069. for (var i in names) {
  26070. if (mesh.name === names[i]) {
  26071. hierarchyIds.push(mesh.id);
  26072. return true;
  26073. }
  26074. }
  26075. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  26076. hierarchyIds.push(mesh.id);
  26077. return true;
  26078. }
  26079. return false;
  26080. };
  26081. var logOperation = function (operation, producer) {
  26082. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  26083. };
  26084. BABYLON.SceneLoader.RegisterPlugin({
  26085. extensions: ".babylon",
  26086. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  26087. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26088. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26089. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26090. // and avoid problems with multiple concurrent .babylon loads.
  26091. var log = "importMesh has failed JSON parse";
  26092. try {
  26093. var parsedData = JSON.parse(data);
  26094. log = "";
  26095. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26096. var loadedSkeletonsIds = [];
  26097. var loadedMaterialsIds = [];
  26098. var hierarchyIds = [];
  26099. var index;
  26100. var cache;
  26101. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26102. var parsedMesh = parsedData.meshes[index];
  26103. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  26104. if (meshesNames instanceof Array) {
  26105. // Remove found mesh name from list.
  26106. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  26107. }
  26108. //Geometry?
  26109. if (parsedMesh.geometryId) {
  26110. //does the file contain geometries?
  26111. if (parsedData.geometries) {
  26112. //find the correct geometry and add it to the scene
  26113. var found = false;
  26114. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  26115. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  26116. return;
  26117. }
  26118. else {
  26119. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  26120. if (parsedGeometryData.id === parsedMesh.geometryId) {
  26121. switch (geometryType) {
  26122. case "boxes":
  26123. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  26124. break;
  26125. case "spheres":
  26126. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  26127. break;
  26128. case "cylinders":
  26129. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  26130. break;
  26131. case "toruses":
  26132. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26133. break;
  26134. case "grounds":
  26135. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26136. break;
  26137. case "planes":
  26138. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26139. break;
  26140. case "torusKnots":
  26141. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26142. break;
  26143. case "vertexData":
  26144. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26145. break;
  26146. }
  26147. found = true;
  26148. }
  26149. });
  26150. }
  26151. });
  26152. if (!found) {
  26153. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26154. }
  26155. }
  26156. }
  26157. // Material ?
  26158. if (parsedMesh.materialId) {
  26159. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26160. if (!materialFound && parsedData.multiMaterials) {
  26161. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26162. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26163. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26164. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26165. var subMatId = parsedMultiMaterial.materials[matIndex];
  26166. loadedMaterialsIds.push(subMatId);
  26167. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26168. log += "\n\tMaterial " + mat.toString(fullDetails);
  26169. }
  26170. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26171. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26172. materialFound = true;
  26173. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26174. break;
  26175. }
  26176. }
  26177. }
  26178. if (!materialFound) {
  26179. loadedMaterialsIds.push(parsedMesh.materialId);
  26180. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  26181. if (!mat) {
  26182. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  26183. }
  26184. else {
  26185. log += "\n\tMaterial " + mat.toString(fullDetails);
  26186. }
  26187. }
  26188. }
  26189. // Skeleton ?
  26190. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  26191. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  26192. if (!skeletonAlreadyLoaded) {
  26193. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  26194. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  26195. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  26196. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26197. skeletons.push(skeleton);
  26198. loadedSkeletonsIds.push(parsedSkeleton.id);
  26199. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  26200. }
  26201. }
  26202. }
  26203. }
  26204. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26205. meshes.push(mesh);
  26206. log += "\n\tMesh " + mesh.toString(fullDetails);
  26207. }
  26208. }
  26209. // Connecting parents
  26210. var currentMesh;
  26211. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26212. currentMesh = scene.meshes[index];
  26213. if (currentMesh._waitingParentId) {
  26214. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  26215. currentMesh._waitingParentId = undefined;
  26216. }
  26217. }
  26218. // freeze and compute world matrix application
  26219. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26220. currentMesh = scene.meshes[index];
  26221. if (currentMesh._waitingFreezeWorldMatrix) {
  26222. currentMesh.freezeWorldMatrix();
  26223. currentMesh._waitingFreezeWorldMatrix = undefined;
  26224. }
  26225. else {
  26226. currentMesh.computeWorldMatrix(true);
  26227. }
  26228. }
  26229. // Particles
  26230. if (parsedData.particleSystems) {
  26231. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26232. var parsedParticleSystem = parsedData.particleSystems[index];
  26233. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  26234. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  26235. }
  26236. }
  26237. }
  26238. return true;
  26239. }
  26240. catch (err) {
  26241. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  26242. log = null;
  26243. throw err;
  26244. }
  26245. finally {
  26246. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26247. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26248. }
  26249. }
  26250. },
  26251. load: function (scene, data, rootUrl) {
  26252. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26253. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26254. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26255. // and avoid problems with multiple concurrent .babylon loads.
  26256. var log = "importScene has failed JSON parse";
  26257. try {
  26258. var parsedData = JSON.parse(data);
  26259. log = "";
  26260. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26261. // Scene
  26262. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  26263. scene.autoClear = parsedData.autoClear;
  26264. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  26265. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  26266. if (parsedData.gravity) {
  26267. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  26268. }
  26269. // Fog
  26270. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  26271. scene.fogMode = parsedData.fogMode;
  26272. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  26273. scene.fogStart = parsedData.fogStart;
  26274. scene.fogEnd = parsedData.fogEnd;
  26275. scene.fogDensity = parsedData.fogDensity;
  26276. log += "\tFog mode for scene: ";
  26277. switch (scene.fogMode) {
  26278. // getters not compiling, so using hardcoded
  26279. case 1:
  26280. log += "exp\n";
  26281. break;
  26282. case 2:
  26283. log += "exp2\n";
  26284. break;
  26285. case 3:
  26286. log += "linear\n";
  26287. break;
  26288. }
  26289. }
  26290. //Physics
  26291. if (parsedData.physicsEnabled) {
  26292. var physicsPlugin;
  26293. if (parsedData.physicsEngine === "cannon") {
  26294. physicsPlugin = new BABYLON.CannonJSPlugin();
  26295. }
  26296. else if (parsedData.physicsEngine === "oimo") {
  26297. physicsPlugin = new BABYLON.OimoJSPlugin();
  26298. }
  26299. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  26300. //else - default engine, which is currently oimo
  26301. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  26302. scene.enablePhysics(physicsGravity, physicsPlugin);
  26303. }
  26304. //collisions, if defined. otherwise, default is true
  26305. if (parsedData.collisionsEnabled != undefined) {
  26306. scene.collisionsEnabled = parsedData.collisionsEnabled;
  26307. }
  26308. scene.workerCollisions = !!parsedData.workerCollisions;
  26309. var index;
  26310. var cache;
  26311. // Lights
  26312. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  26313. var parsedLight = parsedData.lights[index];
  26314. var light = BABYLON.Light.Parse(parsedLight, scene);
  26315. log += (index === 0 ? "\n\tLights:" : "");
  26316. log += "\n\t\t" + light.toString(fullDetails);
  26317. }
  26318. // Animations
  26319. if (parsedData.animations) {
  26320. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  26321. var parsedAnimation = parsedData.animations[index];
  26322. var animation = BABYLON.Animation.Parse(parsedAnimation);
  26323. scene.animations.push(animation);
  26324. log += (index === 0 ? "\n\tAnimations:" : "");
  26325. log += "\n\t\t" + animation.toString(fullDetails);
  26326. }
  26327. }
  26328. if (parsedData.autoAnimate) {
  26329. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  26330. }
  26331. // Materials
  26332. if (parsedData.materials) {
  26333. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26334. var parsedMaterial = parsedData.materials[index];
  26335. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26336. log += (index === 0 ? "\n\tMaterials:" : "");
  26337. log += "\n\t\t" + mat.toString(fullDetails);
  26338. }
  26339. }
  26340. if (parsedData.multiMaterials) {
  26341. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  26342. var parsedMultiMaterial = parsedData.multiMaterials[index];
  26343. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26344. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  26345. log += "\n\t\t" + mmat.toString(fullDetails);
  26346. }
  26347. }
  26348. // Skeletons
  26349. if (parsedData.skeletons) {
  26350. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  26351. var parsedSkeleton = parsedData.skeletons[index];
  26352. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  26353. log += (index === 0 ? "\n\tSkeletons:" : "");
  26354. log += "\n\t\t" + skeleton.toString(fullDetails);
  26355. }
  26356. }
  26357. // Geometries
  26358. var geometries = parsedData.geometries;
  26359. if (geometries) {
  26360. // Boxes
  26361. var boxes = geometries.boxes;
  26362. if (boxes) {
  26363. for (index = 0, cache = boxes.length; index < cache; index++) {
  26364. var parsedBox = boxes[index];
  26365. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  26366. }
  26367. }
  26368. // Spheres
  26369. var spheres = geometries.spheres;
  26370. if (spheres) {
  26371. for (index = 0, cache = spheres.length; index < cache; index++) {
  26372. var parsedSphere = spheres[index];
  26373. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  26374. }
  26375. }
  26376. // Cylinders
  26377. var cylinders = geometries.cylinders;
  26378. if (cylinders) {
  26379. for (index = 0, cache = cylinders.length; index < cache; index++) {
  26380. var parsedCylinder = cylinders[index];
  26381. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  26382. }
  26383. }
  26384. // Toruses
  26385. var toruses = geometries.toruses;
  26386. if (toruses) {
  26387. for (index = 0, cache = toruses.length; index < cache; index++) {
  26388. var parsedTorus = toruses[index];
  26389. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  26390. }
  26391. }
  26392. // Grounds
  26393. var grounds = geometries.grounds;
  26394. if (grounds) {
  26395. for (index = 0, cache = grounds.length; index < cache; index++) {
  26396. var parsedGround = grounds[index];
  26397. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  26398. }
  26399. }
  26400. // Planes
  26401. var planes = geometries.planes;
  26402. if (planes) {
  26403. for (index = 0, cache = planes.length; index < cache; index++) {
  26404. var parsedPlane = planes[index];
  26405. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  26406. }
  26407. }
  26408. // TorusKnots
  26409. var torusKnots = geometries.torusKnots;
  26410. if (torusKnots) {
  26411. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  26412. var parsedTorusKnot = torusKnots[index];
  26413. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  26414. }
  26415. }
  26416. // VertexData
  26417. var vertexData = geometries.vertexData;
  26418. if (vertexData) {
  26419. for (index = 0, cache = vertexData.length; index < cache; index++) {
  26420. var parsedVertexData = vertexData[index];
  26421. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  26422. }
  26423. }
  26424. }
  26425. // Meshes
  26426. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26427. var parsedMesh = parsedData.meshes[index];
  26428. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  26429. log += (index === 0 ? "\n\tMeshes:" : "");
  26430. log += "\n\t\t" + mesh.toString(fullDetails);
  26431. }
  26432. // Cameras
  26433. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  26434. var parsedCamera = parsedData.cameras[index];
  26435. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  26436. log += (index === 0 ? "\n\tCameras:" : "");
  26437. log += "\n\t\t" + camera.toString(fullDetails);
  26438. }
  26439. if (parsedData.activeCameraID) {
  26440. scene.setActiveCameraByID(parsedData.activeCameraID);
  26441. }
  26442. // Browsing all the graph to connect the dots
  26443. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  26444. var camera = scene.cameras[index];
  26445. if (camera._waitingParentId) {
  26446. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  26447. camera._waitingParentId = undefined;
  26448. }
  26449. }
  26450. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  26451. var light = scene.lights[index];
  26452. if (light._waitingParentId) {
  26453. light.parent = scene.getLastEntryByID(light._waitingParentId);
  26454. light._waitingParentId = undefined;
  26455. }
  26456. }
  26457. // Sounds
  26458. var loadedSounds = [];
  26459. var loadedSound;
  26460. if (BABYLON.AudioEngine && parsedData.sounds) {
  26461. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  26462. var parsedSound = parsedData.sounds[index];
  26463. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26464. if (!parsedSound.url)
  26465. parsedSound.url = parsedSound.name;
  26466. if (!loadedSounds[parsedSound.url]) {
  26467. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  26468. loadedSounds[parsedSound.url] = loadedSound;
  26469. }
  26470. else {
  26471. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  26472. }
  26473. }
  26474. else {
  26475. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  26476. }
  26477. }
  26478. }
  26479. loadedSounds = [];
  26480. // Connect parents & children and parse actions
  26481. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26482. var mesh = scene.meshes[index];
  26483. if (mesh._waitingParentId) {
  26484. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  26485. mesh._waitingParentId = undefined;
  26486. }
  26487. if (mesh._waitingActions) {
  26488. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  26489. mesh._waitingActions = undefined;
  26490. }
  26491. }
  26492. // freeze world matrix application
  26493. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  26494. var currentMesh = scene.meshes[index];
  26495. if (currentMesh._waitingFreezeWorldMatrix) {
  26496. currentMesh.freezeWorldMatrix();
  26497. currentMesh._waitingFreezeWorldMatrix = undefined;
  26498. }
  26499. else {
  26500. currentMesh.computeWorldMatrix(true);
  26501. }
  26502. }
  26503. // Particles Systems
  26504. if (parsedData.particleSystems) {
  26505. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  26506. var parsedParticleSystem = parsedData.particleSystems[index];
  26507. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  26508. }
  26509. }
  26510. // Lens flares
  26511. if (parsedData.lensFlareSystems) {
  26512. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  26513. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  26514. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  26515. }
  26516. }
  26517. // Shadows
  26518. if (parsedData.shadowGenerators) {
  26519. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  26520. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  26521. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  26522. }
  26523. }
  26524. // Actions (scene)
  26525. if (parsedData.actions) {
  26526. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  26527. }
  26528. // Finish
  26529. return true;
  26530. }
  26531. catch (err) {
  26532. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  26533. log = null;
  26534. throw err;
  26535. }
  26536. finally {
  26537. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  26538. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  26539. }
  26540. }
  26541. }
  26542. });
  26543. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26544. })(BABYLON || (BABYLON = {}));
  26545. var BABYLON;
  26546. (function (BABYLON) {
  26547. var SpriteManager = (function () {
  26548. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  26549. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26550. this.name = name;
  26551. this.sprites = new Array();
  26552. this.renderingGroupId = 0;
  26553. this.layerMask = 0x0FFFFFFF;
  26554. this.fogEnabled = true;
  26555. this.isPickable = false;
  26556. /**
  26557. * An event triggered when the manager is disposed.
  26558. * @type {BABYLON.Observable}
  26559. */
  26560. this.onDisposeObservable = new BABYLON.Observable();
  26561. this._vertexBuffers = {};
  26562. this._capacity = capacity;
  26563. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  26564. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26565. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  26566. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  26567. if (cellSize.width) {
  26568. this.cellWidth = cellSize.width;
  26569. this.cellHeight = cellSize.height;
  26570. }
  26571. else {
  26572. this.cellWidth = cellSize;
  26573. this.cellHeight = cellSize;
  26574. }
  26575. this._scene = scene;
  26576. this._scene.spriteManagers.push(this);
  26577. var indices = [];
  26578. var index = 0;
  26579. for (var count = 0; count < capacity; count++) {
  26580. indices.push(index);
  26581. indices.push(index + 1);
  26582. indices.push(index + 2);
  26583. indices.push(index);
  26584. indices.push(index + 2);
  26585. indices.push(index + 3);
  26586. index += 4;
  26587. }
  26588. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  26589. // VBO
  26590. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  26591. this._vertexData = new Float32Array(capacity * 16 * 4);
  26592. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  26593. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  26594. var options = this._buffer.createVertexBuffer("options", 4, 4);
  26595. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  26596. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  26597. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  26598. this._vertexBuffers["options"] = options;
  26599. this._vertexBuffers["cellInfo"] = cellInfo;
  26600. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  26601. // Effects
  26602. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  26603. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  26604. }
  26605. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  26606. set: function (callback) {
  26607. if (this._onDisposeObserver) {
  26608. this.onDisposeObservable.remove(this._onDisposeObserver);
  26609. }
  26610. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26611. },
  26612. enumerable: true,
  26613. configurable: true
  26614. });
  26615. Object.defineProperty(SpriteManager.prototype, "texture", {
  26616. get: function () {
  26617. return this._spriteTexture;
  26618. },
  26619. set: function (value) {
  26620. this._spriteTexture = value;
  26621. },
  26622. enumerable: true,
  26623. configurable: true
  26624. });
  26625. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  26626. var arrayOffset = index * 16;
  26627. if (offsetX === 0)
  26628. offsetX = this._epsilon;
  26629. else if (offsetX === 1)
  26630. offsetX = 1 - this._epsilon;
  26631. if (offsetY === 0)
  26632. offsetY = this._epsilon;
  26633. else if (offsetY === 1)
  26634. offsetY = 1 - this._epsilon;
  26635. this._vertexData[arrayOffset] = sprite.position.x;
  26636. this._vertexData[arrayOffset + 1] = sprite.position.y;
  26637. this._vertexData[arrayOffset + 2] = sprite.position.z;
  26638. this._vertexData[arrayOffset + 3] = sprite.angle;
  26639. this._vertexData[arrayOffset + 4] = sprite.width;
  26640. this._vertexData[arrayOffset + 5] = sprite.height;
  26641. this._vertexData[arrayOffset + 6] = offsetX;
  26642. this._vertexData[arrayOffset + 7] = offsetY;
  26643. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  26644. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  26645. var offset = (sprite.cellIndex / rowSize) >> 0;
  26646. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  26647. this._vertexData[arrayOffset + 11] = offset;
  26648. // Color
  26649. this._vertexData[arrayOffset + 12] = sprite.color.r;
  26650. this._vertexData[arrayOffset + 13] = sprite.color.g;
  26651. this._vertexData[arrayOffset + 14] = sprite.color.b;
  26652. this._vertexData[arrayOffset + 15] = sprite.color.a;
  26653. };
  26654. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  26655. var count = Math.min(this._capacity, this.sprites.length);
  26656. var min = BABYLON.Vector3.Zero();
  26657. var max = BABYLON.Vector3.Zero();
  26658. var distance = Number.MAX_VALUE;
  26659. var currentSprite;
  26660. var cameraSpacePosition = BABYLON.Vector3.Zero();
  26661. var cameraView = camera.getViewMatrix();
  26662. for (var index = 0; index < count; index++) {
  26663. var sprite = this.sprites[index];
  26664. if (!sprite) {
  26665. continue;
  26666. }
  26667. if (predicate) {
  26668. if (!predicate(sprite)) {
  26669. continue;
  26670. }
  26671. }
  26672. else if (!sprite.isPickable) {
  26673. continue;
  26674. }
  26675. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  26676. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  26677. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  26678. if (ray.intersectsBoxMinMax(min, max)) {
  26679. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  26680. if (distance > currentDistance) {
  26681. distance = currentDistance;
  26682. currentSprite = sprite;
  26683. if (fastCheck) {
  26684. break;
  26685. }
  26686. }
  26687. }
  26688. }
  26689. if (currentSprite) {
  26690. var result = new BABYLON.PickingInfo();
  26691. result.hit = true;
  26692. result.pickedSprite = currentSprite;
  26693. result.distance = distance;
  26694. return result;
  26695. }
  26696. return null;
  26697. };
  26698. SpriteManager.prototype.render = function () {
  26699. // Check
  26700. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  26701. return;
  26702. var engine = this._scene.getEngine();
  26703. var baseSize = this._spriteTexture.getBaseSize();
  26704. // Sprites
  26705. var deltaTime = engine.getDeltaTime();
  26706. var max = Math.min(this._capacity, this.sprites.length);
  26707. var rowSize = baseSize.width / this.cellWidth;
  26708. var offset = 0;
  26709. for (var index = 0; index < max; index++) {
  26710. var sprite = this.sprites[index];
  26711. if (!sprite) {
  26712. continue;
  26713. }
  26714. sprite._animate(deltaTime);
  26715. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  26716. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  26717. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  26718. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  26719. }
  26720. this._buffer.update(this._vertexData);
  26721. // Render
  26722. var effect = this._effectBase;
  26723. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26724. effect = this._effectFog;
  26725. }
  26726. engine.enableEffect(effect);
  26727. var viewMatrix = this._scene.getViewMatrix();
  26728. effect.setTexture("diffuseSampler", this._spriteTexture);
  26729. effect.setMatrix("view", viewMatrix);
  26730. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  26731. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  26732. // Fog
  26733. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26734. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  26735. effect.setColor3("vFogColor", this._scene.fogColor);
  26736. }
  26737. // VBOs
  26738. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  26739. // Draw order
  26740. engine.setDepthFunctionToLessOrEqual();
  26741. effect.setBool("alphaTest", true);
  26742. engine.setColorWrite(false);
  26743. engine.draw(true, 0, max * 6);
  26744. engine.setColorWrite(true);
  26745. effect.setBool("alphaTest", false);
  26746. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  26747. engine.draw(true, 0, max * 6);
  26748. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26749. };
  26750. SpriteManager.prototype.dispose = function () {
  26751. if (this._buffer) {
  26752. this._buffer.dispose();
  26753. this._buffer = null;
  26754. }
  26755. if (this._indexBuffer) {
  26756. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26757. this._indexBuffer = null;
  26758. }
  26759. if (this._spriteTexture) {
  26760. this._spriteTexture.dispose();
  26761. this._spriteTexture = null;
  26762. }
  26763. // Remove from scene
  26764. var index = this._scene.spriteManagers.indexOf(this);
  26765. this._scene.spriteManagers.splice(index, 1);
  26766. // Callback
  26767. this.onDisposeObservable.notifyObservers(this);
  26768. this.onDisposeObservable.clear();
  26769. };
  26770. return SpriteManager;
  26771. }());
  26772. BABYLON.SpriteManager = SpriteManager;
  26773. })(BABYLON || (BABYLON = {}));
  26774. var BABYLON;
  26775. (function (BABYLON) {
  26776. var Sprite = (function () {
  26777. function Sprite(name, manager) {
  26778. this.name = name;
  26779. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  26780. this.width = 1.0;
  26781. this.height = 1.0;
  26782. this.angle = 0;
  26783. this.cellIndex = 0;
  26784. this.invertU = 0;
  26785. this.invertV = 0;
  26786. this.animations = new Array();
  26787. this.isPickable = false;
  26788. this._animationStarted = false;
  26789. this._loopAnimation = false;
  26790. this._fromIndex = 0;
  26791. this._toIndex = 0;
  26792. this._delay = 0;
  26793. this._direction = 1;
  26794. this._frameCount = 0;
  26795. this._time = 0;
  26796. this._manager = manager;
  26797. this._manager.sprites.push(this);
  26798. this.position = BABYLON.Vector3.Zero();
  26799. }
  26800. Object.defineProperty(Sprite.prototype, "size", {
  26801. get: function () {
  26802. return this.width;
  26803. },
  26804. set: function (value) {
  26805. this.width = value;
  26806. this.height = value;
  26807. },
  26808. enumerable: true,
  26809. configurable: true
  26810. });
  26811. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  26812. this._fromIndex = from;
  26813. this._toIndex = to;
  26814. this._loopAnimation = loop;
  26815. this._delay = delay;
  26816. this._animationStarted = true;
  26817. this._direction = from < to ? 1 : -1;
  26818. this.cellIndex = from;
  26819. this._time = 0;
  26820. this._onAnimationEnd = onAnimationEnd;
  26821. };
  26822. Sprite.prototype.stopAnimation = function () {
  26823. this._animationStarted = false;
  26824. };
  26825. Sprite.prototype._animate = function (deltaTime) {
  26826. if (!this._animationStarted)
  26827. return;
  26828. this._time += deltaTime;
  26829. if (this._time > this._delay) {
  26830. this._time = this._time % this._delay;
  26831. this.cellIndex += this._direction;
  26832. if (this.cellIndex === this._toIndex) {
  26833. if (this._loopAnimation) {
  26834. this.cellIndex = this._fromIndex;
  26835. }
  26836. else {
  26837. this._animationStarted = false;
  26838. if (this._onAnimationEnd) {
  26839. this._onAnimationEnd();
  26840. }
  26841. if (this.disposeWhenFinishedAnimating) {
  26842. this.dispose();
  26843. }
  26844. }
  26845. }
  26846. }
  26847. };
  26848. Sprite.prototype.dispose = function () {
  26849. for (var i = 0; i < this._manager.sprites.length; i++) {
  26850. if (this._manager.sprites[i] == this) {
  26851. this._manager.sprites.splice(i, 1);
  26852. }
  26853. }
  26854. };
  26855. return Sprite;
  26856. }());
  26857. BABYLON.Sprite = Sprite;
  26858. })(BABYLON || (BABYLON = {}));
  26859. var BABYLON;
  26860. (function (BABYLON) {
  26861. var Layer = (function () {
  26862. function Layer(name, imgUrl, scene, isBackground, color) {
  26863. this.name = name;
  26864. this.scale = new BABYLON.Vector2(1, 1);
  26865. this.offset = new BABYLON.Vector2(0, 0);
  26866. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  26867. this._vertexBuffers = {};
  26868. // Events
  26869. /**
  26870. * An event triggered when the layer is disposed.
  26871. * @type {BABYLON.Observable}
  26872. */
  26873. this.onDisposeObservable = new BABYLON.Observable();
  26874. /**
  26875. * An event triggered before rendering the scene
  26876. * @type {BABYLON.Observable}
  26877. */
  26878. this.onBeforeRenderObservable = new BABYLON.Observable();
  26879. /**
  26880. * An event triggered after rendering the scene
  26881. * @type {BABYLON.Observable}
  26882. */
  26883. this.onAfterRenderObservable = new BABYLON.Observable();
  26884. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  26885. this.isBackground = isBackground === undefined ? true : isBackground;
  26886. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  26887. this._scene = scene;
  26888. this._scene.layers.push(this);
  26889. var engine = scene.getEngine();
  26890. // VBO
  26891. var vertices = [];
  26892. vertices.push(1, 1);
  26893. vertices.push(-1, 1);
  26894. vertices.push(-1, -1);
  26895. vertices.push(1, -1);
  26896. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  26897. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  26898. // Indices
  26899. var indices = [];
  26900. indices.push(0);
  26901. indices.push(1);
  26902. indices.push(2);
  26903. indices.push(0);
  26904. indices.push(2);
  26905. indices.push(3);
  26906. this._indexBuffer = engine.createIndexBuffer(indices);
  26907. // Effects
  26908. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  26909. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  26910. }
  26911. Object.defineProperty(Layer.prototype, "onDispose", {
  26912. set: function (callback) {
  26913. if (this._onDisposeObserver) {
  26914. this.onDisposeObservable.remove(this._onDisposeObserver);
  26915. }
  26916. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26917. },
  26918. enumerable: true,
  26919. configurable: true
  26920. });
  26921. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  26922. set: function (callback) {
  26923. if (this._onBeforeRenderObserver) {
  26924. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  26925. }
  26926. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  26927. },
  26928. enumerable: true,
  26929. configurable: true
  26930. });
  26931. Object.defineProperty(Layer.prototype, "onAfterRender", {
  26932. set: function (callback) {
  26933. if (this._onAfterRenderObserver) {
  26934. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  26935. }
  26936. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  26937. },
  26938. enumerable: true,
  26939. configurable: true
  26940. });
  26941. Layer.prototype.render = function () {
  26942. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  26943. // Check
  26944. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  26945. return;
  26946. var engine = this._scene.getEngine();
  26947. this.onBeforeRenderObservable.notifyObservers(this);
  26948. // Render
  26949. engine.enableEffect(currentEffect);
  26950. engine.setState(false);
  26951. // Texture
  26952. currentEffect.setTexture("textureSampler", this.texture);
  26953. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  26954. // Color
  26955. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  26956. // Scale / offset
  26957. currentEffect.setVector2("offset", this.offset);
  26958. currentEffect.setVector2("scale", this.scale);
  26959. // VBOs
  26960. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  26961. // Draw order
  26962. if (!this._alphaTestEffect) {
  26963. engine.setAlphaMode(this.alphaBlendingMode);
  26964. engine.draw(true, 0, 6);
  26965. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  26966. }
  26967. else {
  26968. engine.draw(true, 0, 6);
  26969. }
  26970. this.onAfterRenderObservable.notifyObservers(this);
  26971. };
  26972. Layer.prototype.dispose = function () {
  26973. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  26974. if (vertexBuffer) {
  26975. vertexBuffer.dispose();
  26976. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  26977. }
  26978. if (this._indexBuffer) {
  26979. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  26980. this._indexBuffer = null;
  26981. }
  26982. if (this.texture) {
  26983. this.texture.dispose();
  26984. this.texture = null;
  26985. }
  26986. // Remove from scene
  26987. var index = this._scene.layers.indexOf(this);
  26988. this._scene.layers.splice(index, 1);
  26989. // Callback
  26990. this.onDisposeObservable.notifyObservers(this);
  26991. this.onDisposeObservable.clear();
  26992. this.onAfterRenderObservable.clear();
  26993. this.onBeforeRenderObservable.clear();
  26994. };
  26995. return Layer;
  26996. }());
  26997. BABYLON.Layer = Layer;
  26998. })(BABYLON || (BABYLON = {}));
  26999. var BABYLON;
  27000. (function (BABYLON) {
  27001. var Particle = (function () {
  27002. function Particle() {
  27003. this.position = BABYLON.Vector3.Zero();
  27004. this.direction = BABYLON.Vector3.Zero();
  27005. this.color = new BABYLON.Color4(0, 0, 0, 0);
  27006. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  27007. this.lifeTime = 1.0;
  27008. this.age = 0;
  27009. this.size = 0;
  27010. this.angle = 0;
  27011. this.angularSpeed = 0;
  27012. }
  27013. Particle.prototype.copyTo = function (other) {
  27014. other.position.copyFrom(this.position);
  27015. other.direction.copyFrom(this.direction);
  27016. other.color.copyFrom(this.color);
  27017. other.colorStep.copyFrom(this.colorStep);
  27018. other.lifeTime = this.lifeTime;
  27019. other.age = this.age;
  27020. other.size = this.size;
  27021. other.angle = this.angle;
  27022. other.angularSpeed = this.angularSpeed;
  27023. };
  27024. return Particle;
  27025. }());
  27026. BABYLON.Particle = Particle;
  27027. })(BABYLON || (BABYLON = {}));
  27028. var BABYLON;
  27029. (function (BABYLON) {
  27030. var randomNumber = function (min, max) {
  27031. if (min === max) {
  27032. return (min);
  27033. }
  27034. var random = Math.random();
  27035. return ((random * (max - min)) + min);
  27036. };
  27037. var ParticleSystem = (function () {
  27038. function ParticleSystem(name, capacity, scene, customEffect) {
  27039. var _this = this;
  27040. this.name = name;
  27041. // Members
  27042. this.animations = [];
  27043. this.renderingGroupId = 0;
  27044. this.emitter = null;
  27045. this.emitRate = 10;
  27046. this.manualEmitCount = -1;
  27047. this.updateSpeed = 0.01;
  27048. this.targetStopDuration = 0;
  27049. this.disposeOnStop = false;
  27050. this.minEmitPower = 1;
  27051. this.maxEmitPower = 1;
  27052. this.minLifeTime = 1;
  27053. this.maxLifeTime = 1;
  27054. this.minSize = 1;
  27055. this.maxSize = 1;
  27056. this.minAngularSpeed = 0;
  27057. this.maxAngularSpeed = 0;
  27058. this.layerMask = 0x0FFFFFFF;
  27059. /**
  27060. * An event triggered when the system is disposed.
  27061. * @type {BABYLON.Observable}
  27062. */
  27063. this.onDisposeObservable = new BABYLON.Observable();
  27064. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  27065. this.forceDepthWrite = false;
  27066. this.gravity = BABYLON.Vector3.Zero();
  27067. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  27068. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  27069. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  27070. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  27071. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27072. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27073. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  27074. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27075. this.particles = new Array();
  27076. this._stockParticles = new Array();
  27077. this._newPartsExcess = 0;
  27078. this._vertexBuffers = {};
  27079. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  27080. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  27081. this._scaledDirection = BABYLON.Vector3.Zero();
  27082. this._scaledGravity = BABYLON.Vector3.Zero();
  27083. this._currentRenderId = -1;
  27084. this._started = false;
  27085. this._stopped = false;
  27086. this._actualFrame = 0;
  27087. this.id = name;
  27088. this._capacity = capacity;
  27089. this._scene = scene;
  27090. this._customEffect = customEffect;
  27091. scene.particleSystems.push(this);
  27092. var indices = [];
  27093. var index = 0;
  27094. for (var count = 0; count < capacity; count++) {
  27095. indices.push(index);
  27096. indices.push(index + 1);
  27097. indices.push(index + 2);
  27098. indices.push(index);
  27099. indices.push(index + 2);
  27100. indices.push(index + 3);
  27101. index += 4;
  27102. }
  27103. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27104. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  27105. this._vertexData = new Float32Array(capacity * 11 * 4);
  27106. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  27107. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  27108. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  27109. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  27110. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27111. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27112. this._vertexBuffers["options"] = options;
  27113. // Default behaviors
  27114. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  27115. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  27116. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  27117. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  27118. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  27119. };
  27120. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  27121. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  27122. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  27123. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  27124. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  27125. };
  27126. this.updateFunction = function (particles) {
  27127. for (var index = 0; index < particles.length; index++) {
  27128. var particle = particles[index];
  27129. particle.age += _this._scaledUpdateSpeed;
  27130. if (particle.age >= particle.lifeTime) {
  27131. _this.recycleParticle(particle);
  27132. index--;
  27133. continue;
  27134. }
  27135. else {
  27136. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27137. particle.color.addInPlace(_this._scaledColorStep);
  27138. if (particle.color.a < 0)
  27139. particle.color.a = 0;
  27140. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27141. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27142. particle.position.addInPlace(_this._scaledDirection);
  27143. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27144. particle.direction.addInPlace(_this._scaledGravity);
  27145. }
  27146. }
  27147. };
  27148. }
  27149. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27150. set: function (callback) {
  27151. if (this._onDisposeObserver) {
  27152. this.onDisposeObservable.remove(this._onDisposeObserver);
  27153. }
  27154. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27155. },
  27156. enumerable: true,
  27157. configurable: true
  27158. });
  27159. ParticleSystem.prototype.recycleParticle = function (particle) {
  27160. var lastParticle = this.particles.pop();
  27161. if (lastParticle !== particle) {
  27162. lastParticle.copyTo(particle);
  27163. this._stockParticles.push(lastParticle);
  27164. }
  27165. };
  27166. ParticleSystem.prototype.getCapacity = function () {
  27167. return this._capacity;
  27168. };
  27169. ParticleSystem.prototype.isAlive = function () {
  27170. return this._alive;
  27171. };
  27172. ParticleSystem.prototype.isStarted = function () {
  27173. return this._started;
  27174. };
  27175. ParticleSystem.prototype.start = function () {
  27176. this._started = true;
  27177. this._stopped = false;
  27178. this._actualFrame = 0;
  27179. };
  27180. ParticleSystem.prototype.stop = function () {
  27181. this._stopped = true;
  27182. };
  27183. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  27184. var offset = index * 11;
  27185. this._vertexData[offset] = particle.position.x;
  27186. this._vertexData[offset + 1] = particle.position.y;
  27187. this._vertexData[offset + 2] = particle.position.z;
  27188. this._vertexData[offset + 3] = particle.color.r;
  27189. this._vertexData[offset + 4] = particle.color.g;
  27190. this._vertexData[offset + 5] = particle.color.b;
  27191. this._vertexData[offset + 6] = particle.color.a;
  27192. this._vertexData[offset + 7] = particle.angle;
  27193. this._vertexData[offset + 8] = particle.size;
  27194. this._vertexData[offset + 9] = offsetX;
  27195. this._vertexData[offset + 10] = offsetY;
  27196. };
  27197. ParticleSystem.prototype._update = function (newParticles) {
  27198. // Update current
  27199. this._alive = this.particles.length > 0;
  27200. this.updateFunction(this.particles);
  27201. // Add new ones
  27202. var worldMatrix;
  27203. if (this.emitter.position) {
  27204. worldMatrix = this.emitter.getWorldMatrix();
  27205. }
  27206. else {
  27207. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  27208. }
  27209. var particle;
  27210. for (var index = 0; index < newParticles; index++) {
  27211. if (this.particles.length === this._capacity) {
  27212. break;
  27213. }
  27214. if (this._stockParticles.length !== 0) {
  27215. particle = this._stockParticles.pop();
  27216. particle.age = 0;
  27217. }
  27218. else {
  27219. particle = new BABYLON.Particle();
  27220. }
  27221. this.particles.push(particle);
  27222. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  27223. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  27224. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  27225. particle.size = randomNumber(this.minSize, this.maxSize);
  27226. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  27227. this.startPositionFunction(worldMatrix, particle.position, particle);
  27228. var step = randomNumber(0, 1.0);
  27229. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  27230. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  27231. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  27232. }
  27233. };
  27234. ParticleSystem.prototype._getEffect = function () {
  27235. if (this._customEffect) {
  27236. return this._customEffect;
  27237. }
  27238. ;
  27239. var defines = [];
  27240. if (this._scene.clipPlane) {
  27241. defines.push("#define CLIPPLANE");
  27242. }
  27243. // Effect
  27244. var join = defines.join("\n");
  27245. if (this._cachedDefines !== join) {
  27246. this._cachedDefines = join;
  27247. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  27248. }
  27249. return this._effect;
  27250. };
  27251. ParticleSystem.prototype.animate = function () {
  27252. if (!this._started)
  27253. return;
  27254. var effect = this._getEffect();
  27255. // Check
  27256. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  27257. return;
  27258. if (this._currentRenderId === this._scene.getRenderId()) {
  27259. return;
  27260. }
  27261. this._currentRenderId = this._scene.getRenderId();
  27262. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  27263. // determine the number of particles we need to create
  27264. var newParticles;
  27265. if (this.manualEmitCount > -1) {
  27266. newParticles = this.manualEmitCount;
  27267. this._newPartsExcess = 0;
  27268. this.manualEmitCount = 0;
  27269. }
  27270. else {
  27271. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  27272. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  27273. }
  27274. if (this._newPartsExcess > 1.0) {
  27275. newParticles += this._newPartsExcess >> 0;
  27276. this._newPartsExcess -= this._newPartsExcess >> 0;
  27277. }
  27278. this._alive = false;
  27279. if (!this._stopped) {
  27280. this._actualFrame += this._scaledUpdateSpeed;
  27281. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  27282. this.stop();
  27283. }
  27284. else {
  27285. newParticles = 0;
  27286. }
  27287. this._update(newParticles);
  27288. // Stopped?
  27289. if (this._stopped) {
  27290. if (!this._alive) {
  27291. this._started = false;
  27292. if (this.disposeOnStop) {
  27293. this._scene._toBeDisposed.push(this);
  27294. }
  27295. }
  27296. }
  27297. // Update VBO
  27298. var offset = 0;
  27299. for (var index = 0; index < this.particles.length; index++) {
  27300. var particle = this.particles[index];
  27301. this._appendParticleVertex(offset++, particle, 0, 0);
  27302. this._appendParticleVertex(offset++, particle, 1, 0);
  27303. this._appendParticleVertex(offset++, particle, 1, 1);
  27304. this._appendParticleVertex(offset++, particle, 0, 1);
  27305. }
  27306. this._vertexBuffer.update(this._vertexData);
  27307. };
  27308. ParticleSystem.prototype.render = function () {
  27309. var effect = this._getEffect();
  27310. // Check
  27311. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  27312. return 0;
  27313. var engine = this._scene.getEngine();
  27314. // Render
  27315. engine.enableEffect(effect);
  27316. engine.setState(false);
  27317. var viewMatrix = this._scene.getViewMatrix();
  27318. effect.setTexture("diffuseSampler", this.particleTexture);
  27319. effect.setMatrix("view", viewMatrix);
  27320. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27321. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  27322. if (this._scene.clipPlane) {
  27323. var clipPlane = this._scene.clipPlane;
  27324. var invView = viewMatrix.clone();
  27325. invView.invert();
  27326. effect.setMatrix("invView", invView);
  27327. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  27328. }
  27329. // VBOs
  27330. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27331. // Draw order
  27332. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  27333. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  27334. }
  27335. else {
  27336. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27337. }
  27338. if (this.forceDepthWrite) {
  27339. engine.setDepthWrite(true);
  27340. }
  27341. engine.draw(true, 0, this.particles.length * 6);
  27342. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27343. return this.particles.length;
  27344. };
  27345. ParticleSystem.prototype.dispose = function () {
  27346. if (this._vertexBuffer) {
  27347. this._vertexBuffer.dispose();
  27348. this._vertexBuffer = null;
  27349. }
  27350. if (this._indexBuffer) {
  27351. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27352. this._indexBuffer = null;
  27353. }
  27354. if (this.particleTexture) {
  27355. this.particleTexture.dispose();
  27356. this.particleTexture = null;
  27357. }
  27358. // Remove from scene
  27359. var index = this._scene.particleSystems.indexOf(this);
  27360. this._scene.particleSystems.splice(index, 1);
  27361. // Callback
  27362. this.onDisposeObservable.notifyObservers(this);
  27363. this.onDisposeObservable.clear();
  27364. };
  27365. // Clone
  27366. ParticleSystem.prototype.clone = function (name, newEmitter) {
  27367. var result = new ParticleSystem(name, this._capacity, this._scene);
  27368. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  27369. if (newEmitter === undefined) {
  27370. newEmitter = this.emitter;
  27371. }
  27372. result.emitter = newEmitter;
  27373. if (this.particleTexture) {
  27374. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  27375. }
  27376. result.start();
  27377. return result;
  27378. };
  27379. ParticleSystem.prototype.serialize = function () {
  27380. var serializationObject = {};
  27381. serializationObject.name = this.name;
  27382. serializationObject.id = this.id;
  27383. // Emitter
  27384. if (this.emitter.position) {
  27385. serializationObject.emitterId = this.emitter.id;
  27386. }
  27387. else {
  27388. serializationObject.emitter = this.emitter.asArray();
  27389. }
  27390. serializationObject.capacity = this.getCapacity();
  27391. if (this.particleTexture) {
  27392. serializationObject.textureName = this.particleTexture.name;
  27393. }
  27394. // Animations
  27395. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27396. // Particle system
  27397. serializationObject.minAngularSpeed = this.minAngularSpeed;
  27398. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  27399. serializationObject.minSize = this.minSize;
  27400. serializationObject.maxSize = this.maxSize;
  27401. serializationObject.minEmitPower = this.minEmitPower;
  27402. serializationObject.maxEmitPower = this.maxEmitPower;
  27403. serializationObject.minLifeTime = this.minLifeTime;
  27404. serializationObject.maxLifeTime = this.maxLifeTime;
  27405. serializationObject.emitRate = this.emitRate;
  27406. serializationObject.minEmitBox = this.minEmitBox.asArray();
  27407. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  27408. serializationObject.gravity = this.gravity.asArray();
  27409. serializationObject.direction1 = this.direction1.asArray();
  27410. serializationObject.direction2 = this.direction2.asArray();
  27411. serializationObject.color1 = this.color1.asArray();
  27412. serializationObject.color2 = this.color2.asArray();
  27413. serializationObject.colorDead = this.colorDead.asArray();
  27414. serializationObject.updateSpeed = this.updateSpeed;
  27415. serializationObject.targetStopDuration = this.targetStopDuration;
  27416. serializationObject.textureMask = this.textureMask.asArray();
  27417. serializationObject.blendMode = this.blendMode;
  27418. return serializationObject;
  27419. };
  27420. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  27421. var name = parsedParticleSystem.name;
  27422. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  27423. if (parsedParticleSystem.id) {
  27424. particleSystem.id = parsedParticleSystem.id;
  27425. }
  27426. // Texture
  27427. if (parsedParticleSystem.textureName) {
  27428. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  27429. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  27430. }
  27431. // Emitter
  27432. if (parsedParticleSystem.emitterId) {
  27433. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  27434. }
  27435. else {
  27436. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  27437. }
  27438. // Animations
  27439. if (parsedParticleSystem.animations) {
  27440. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  27441. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  27442. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27443. }
  27444. }
  27445. if (parsedParticleSystem.autoAnimate) {
  27446. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  27447. }
  27448. // Particle system
  27449. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  27450. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  27451. particleSystem.minSize = parsedParticleSystem.minSize;
  27452. particleSystem.maxSize = parsedParticleSystem.maxSize;
  27453. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  27454. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  27455. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  27456. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  27457. particleSystem.emitRate = parsedParticleSystem.emitRate;
  27458. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  27459. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  27460. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  27461. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  27462. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  27463. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  27464. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  27465. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  27466. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  27467. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  27468. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  27469. particleSystem.blendMode = parsedParticleSystem.blendMode;
  27470. if (!parsedParticleSystem.preventAutoStart) {
  27471. particleSystem.start();
  27472. }
  27473. return particleSystem;
  27474. };
  27475. // Statics
  27476. ParticleSystem.BLENDMODE_ONEONE = 0;
  27477. ParticleSystem.BLENDMODE_STANDARD = 1;
  27478. return ParticleSystem;
  27479. }());
  27480. BABYLON.ParticleSystem = ParticleSystem;
  27481. })(BABYLON || (BABYLON = {}));
  27482. var BABYLON;
  27483. (function (BABYLON) {
  27484. var AnimationRange = (function () {
  27485. function AnimationRange(name, from, to) {
  27486. this.name = name;
  27487. this.from = from;
  27488. this.to = to;
  27489. }
  27490. AnimationRange.prototype.clone = function () {
  27491. return new AnimationRange(this.name, this.from, this.to);
  27492. };
  27493. return AnimationRange;
  27494. }());
  27495. BABYLON.AnimationRange = AnimationRange;
  27496. /**
  27497. * Composed of a frame, and an action function
  27498. */
  27499. var AnimationEvent = (function () {
  27500. function AnimationEvent(frame, action, onlyOnce) {
  27501. this.frame = frame;
  27502. this.action = action;
  27503. this.onlyOnce = onlyOnce;
  27504. this.isDone = false;
  27505. }
  27506. return AnimationEvent;
  27507. }());
  27508. BABYLON.AnimationEvent = AnimationEvent;
  27509. var PathCursor = (function () {
  27510. function PathCursor(path) {
  27511. this.path = path;
  27512. this._onchange = new Array();
  27513. this.value = 0;
  27514. this.animations = new Array();
  27515. }
  27516. PathCursor.prototype.getPoint = function () {
  27517. var point = this.path.getPointAtLengthPosition(this.value);
  27518. return new BABYLON.Vector3(point.x, 0, point.y);
  27519. };
  27520. PathCursor.prototype.moveAhead = function (step) {
  27521. if (step === void 0) { step = 0.002; }
  27522. this.move(step);
  27523. return this;
  27524. };
  27525. PathCursor.prototype.moveBack = function (step) {
  27526. if (step === void 0) { step = 0.002; }
  27527. this.move(-step);
  27528. return this;
  27529. };
  27530. PathCursor.prototype.move = function (step) {
  27531. if (Math.abs(step) > 1) {
  27532. throw "step size should be less than 1.";
  27533. }
  27534. this.value += step;
  27535. this.ensureLimits();
  27536. this.raiseOnChange();
  27537. return this;
  27538. };
  27539. PathCursor.prototype.ensureLimits = function () {
  27540. while (this.value > 1) {
  27541. this.value -= 1;
  27542. }
  27543. while (this.value < 0) {
  27544. this.value += 1;
  27545. }
  27546. return this;
  27547. };
  27548. // used by animation engine
  27549. PathCursor.prototype.markAsDirty = function (propertyName) {
  27550. this.ensureLimits();
  27551. this.raiseOnChange();
  27552. return this;
  27553. };
  27554. PathCursor.prototype.raiseOnChange = function () {
  27555. var _this = this;
  27556. this._onchange.forEach(function (f) { return f(_this); });
  27557. return this;
  27558. };
  27559. PathCursor.prototype.onchange = function (f) {
  27560. this._onchange.push(f);
  27561. return this;
  27562. };
  27563. return PathCursor;
  27564. }());
  27565. BABYLON.PathCursor = PathCursor;
  27566. var Animation = (function () {
  27567. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  27568. this.name = name;
  27569. this.targetProperty = targetProperty;
  27570. this.framePerSecond = framePerSecond;
  27571. this.dataType = dataType;
  27572. this.loopMode = loopMode;
  27573. this.enableBlending = enableBlending;
  27574. this._offsetsCache = {};
  27575. this._highLimitsCache = {};
  27576. this._stopped = false;
  27577. this._blendingFactor = 0;
  27578. // The set of event that will be linked to this animation
  27579. this._events = new Array();
  27580. this.allowMatricesInterpolation = false;
  27581. this.blendingSpeed = 0.01;
  27582. this._ranges = {};
  27583. this.targetPropertyPath = targetProperty.split(".");
  27584. this.dataType = dataType;
  27585. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  27586. }
  27587. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  27588. var dataType = undefined;
  27589. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  27590. dataType = Animation.ANIMATIONTYPE_FLOAT;
  27591. }
  27592. else if (from instanceof BABYLON.Quaternion) {
  27593. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  27594. }
  27595. else if (from instanceof BABYLON.Vector3) {
  27596. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  27597. }
  27598. else if (from instanceof BABYLON.Vector2) {
  27599. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  27600. }
  27601. else if (from instanceof BABYLON.Color3) {
  27602. dataType = Animation.ANIMATIONTYPE_COLOR3;
  27603. }
  27604. else if (from instanceof BABYLON.Size) {
  27605. dataType = Animation.ANIMATIONTYPE_SIZE;
  27606. }
  27607. if (dataType == undefined) {
  27608. return null;
  27609. }
  27610. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  27611. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  27612. animation.setKeys(keys);
  27613. if (easingFunction !== undefined) {
  27614. animation.setEasingFunction(easingFunction);
  27615. }
  27616. return animation;
  27617. };
  27618. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27619. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27620. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27621. };
  27622. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  27623. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  27624. node.animations.push(animation);
  27625. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  27626. };
  27627. // Methods
  27628. /**
  27629. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27630. */
  27631. Animation.prototype.toString = function (fullDetails) {
  27632. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  27633. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  27634. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  27635. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  27636. if (fullDetails) {
  27637. ret += ", Ranges: {";
  27638. var first = true;
  27639. for (var name in this._ranges) {
  27640. if (first) {
  27641. ret += ", ";
  27642. first = false;
  27643. }
  27644. ret += name;
  27645. }
  27646. ret += "}";
  27647. }
  27648. return ret;
  27649. };
  27650. /**
  27651. * Add an event to this animation.
  27652. */
  27653. Animation.prototype.addEvent = function (event) {
  27654. this._events.push(event);
  27655. };
  27656. /**
  27657. * Remove all events found at the given frame
  27658. * @param frame
  27659. */
  27660. Animation.prototype.removeEvents = function (frame) {
  27661. for (var index = 0; index < this._events.length; index++) {
  27662. if (this._events[index].frame === frame) {
  27663. this._events.splice(index, 1);
  27664. index--;
  27665. }
  27666. }
  27667. };
  27668. Animation.prototype.createRange = function (name, from, to) {
  27669. // check name not already in use; could happen for bones after serialized
  27670. if (!this._ranges[name]) {
  27671. this._ranges[name] = new AnimationRange(name, from, to);
  27672. }
  27673. };
  27674. Animation.prototype.deleteRange = function (name, deleteFrames) {
  27675. if (deleteFrames === void 0) { deleteFrames = true; }
  27676. if (this._ranges[name]) {
  27677. if (deleteFrames) {
  27678. var from = this._ranges[name].from;
  27679. var to = this._ranges[name].to;
  27680. // this loop MUST go high to low for multiple splices to work
  27681. for (var key = this._keys.length - 1; key >= 0; key--) {
  27682. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  27683. this._keys.splice(key, 1);
  27684. }
  27685. }
  27686. }
  27687. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  27688. }
  27689. };
  27690. Animation.prototype.getRange = function (name) {
  27691. return this._ranges[name];
  27692. };
  27693. Animation.prototype.reset = function () {
  27694. this._offsetsCache = {};
  27695. this._highLimitsCache = {};
  27696. this.currentFrame = 0;
  27697. this._blendingFactor = 0;
  27698. this._originalBlendValue = null;
  27699. };
  27700. Animation.prototype.isStopped = function () {
  27701. return this._stopped;
  27702. };
  27703. Animation.prototype.getKeys = function () {
  27704. return this._keys;
  27705. };
  27706. Animation.prototype.getHighestFrame = function () {
  27707. var ret = 0;
  27708. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  27709. if (ret < this._keys[key].frame) {
  27710. ret = this._keys[key].frame;
  27711. }
  27712. }
  27713. return ret;
  27714. };
  27715. Animation.prototype.getEasingFunction = function () {
  27716. return this._easingFunction;
  27717. };
  27718. Animation.prototype.setEasingFunction = function (easingFunction) {
  27719. this._easingFunction = easingFunction;
  27720. };
  27721. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  27722. return startValue + (endValue - startValue) * gradient;
  27723. };
  27724. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  27725. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  27726. };
  27727. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  27728. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  27729. };
  27730. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  27731. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  27732. };
  27733. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  27734. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  27735. };
  27736. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  27737. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  27738. };
  27739. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  27740. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  27741. };
  27742. Animation.prototype.clone = function () {
  27743. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  27744. if (this._keys) {
  27745. clone.setKeys(this._keys);
  27746. }
  27747. if (this._ranges) {
  27748. clone._ranges = {};
  27749. for (var name in this._ranges) {
  27750. clone._ranges[name] = this._ranges[name].clone();
  27751. }
  27752. }
  27753. return clone;
  27754. };
  27755. Animation.prototype.setKeys = function (values) {
  27756. this._keys = values.slice(0);
  27757. this._offsetsCache = {};
  27758. this._highLimitsCache = {};
  27759. };
  27760. Animation.prototype._getKeyValue = function (value) {
  27761. if (typeof value === "function") {
  27762. return value();
  27763. }
  27764. return value;
  27765. };
  27766. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  27767. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  27768. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  27769. }
  27770. this.currentFrame = currentFrame;
  27771. // Try to get a hash to find the right key
  27772. 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));
  27773. if (this._keys[startKey].frame >= currentFrame) {
  27774. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  27775. startKey--;
  27776. }
  27777. }
  27778. for (var key = startKey; key < this._keys.length; key++) {
  27779. if (this._keys[key + 1].frame >= currentFrame) {
  27780. var startValue = this._getKeyValue(this._keys[key].value);
  27781. var endValue = this._getKeyValue(this._keys[key + 1].value);
  27782. // gradient : percent of currentFrame between the frame inf and the frame sup
  27783. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  27784. // check for easingFunction and correction of gradient
  27785. if (this._easingFunction != null) {
  27786. gradient = this._easingFunction.ease(gradient);
  27787. }
  27788. switch (this.dataType) {
  27789. // Float
  27790. case Animation.ANIMATIONTYPE_FLOAT:
  27791. switch (loopMode) {
  27792. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27793. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27794. return this.floatInterpolateFunction(startValue, endValue, gradient);
  27795. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27796. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  27797. }
  27798. break;
  27799. // Quaternion
  27800. case Animation.ANIMATIONTYPE_QUATERNION:
  27801. var quaternion = null;
  27802. switch (loopMode) {
  27803. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27804. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27805. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  27806. break;
  27807. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27808. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27809. break;
  27810. }
  27811. return quaternion;
  27812. // Vector3
  27813. case Animation.ANIMATIONTYPE_VECTOR3:
  27814. switch (loopMode) {
  27815. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27816. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27817. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  27818. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27819. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27820. }
  27821. // Vector2
  27822. case Animation.ANIMATIONTYPE_VECTOR2:
  27823. switch (loopMode) {
  27824. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27825. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27826. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  27827. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27828. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27829. }
  27830. // Size
  27831. case Animation.ANIMATIONTYPE_SIZE:
  27832. switch (loopMode) {
  27833. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27834. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27835. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  27836. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27837. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27838. }
  27839. // Color3
  27840. case Animation.ANIMATIONTYPE_COLOR3:
  27841. switch (loopMode) {
  27842. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27843. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27844. return this.color3InterpolateFunction(startValue, endValue, gradient);
  27845. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27846. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  27847. }
  27848. // Matrix
  27849. case Animation.ANIMATIONTYPE_MATRIX:
  27850. switch (loopMode) {
  27851. case Animation.ANIMATIONLOOPMODE_CYCLE:
  27852. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  27853. if (this.allowMatricesInterpolation) {
  27854. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  27855. }
  27856. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  27857. return startValue;
  27858. }
  27859. default:
  27860. break;
  27861. }
  27862. break;
  27863. }
  27864. }
  27865. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  27866. };
  27867. Animation.prototype.setValue = function (currentValue, blend) {
  27868. if (blend === void 0) { blend = false; }
  27869. // Set value
  27870. var path;
  27871. var destination;
  27872. if (this.targetPropertyPath.length > 1) {
  27873. var property = this._target[this.targetPropertyPath[0]];
  27874. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  27875. property = property[this.targetPropertyPath[index]];
  27876. }
  27877. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  27878. destination = property;
  27879. }
  27880. else {
  27881. path = this.targetPropertyPath[0];
  27882. destination = this._target;
  27883. }
  27884. // Blending
  27885. if (this.enableBlending && this._blendingFactor <= 1.0) {
  27886. if (!this._originalBlendValue) {
  27887. if (destination[path].clone) {
  27888. this._originalBlendValue = destination[path].clone();
  27889. }
  27890. else {
  27891. this._originalBlendValue = destination[path];
  27892. }
  27893. }
  27894. if (this._originalBlendValue.prototype) {
  27895. if (this._originalBlendValue.prototype.Lerp) {
  27896. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  27897. }
  27898. else {
  27899. destination[path] = currentValue;
  27900. }
  27901. }
  27902. else if (this._originalBlendValue.m) {
  27903. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  27904. }
  27905. else {
  27906. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  27907. }
  27908. this._blendingFactor += this.blendingSpeed;
  27909. }
  27910. else {
  27911. destination[path] = currentValue;
  27912. }
  27913. if (this._target.markAsDirty) {
  27914. this._target.markAsDirty(this.targetProperty);
  27915. }
  27916. };
  27917. Animation.prototype.goToFrame = function (frame) {
  27918. if (frame < this._keys[0].frame) {
  27919. frame = this._keys[0].frame;
  27920. }
  27921. else if (frame > this._keys[this._keys.length - 1].frame) {
  27922. frame = this._keys[this._keys.length - 1].frame;
  27923. }
  27924. var currentValue = this._interpolate(frame, 0, this.loopMode);
  27925. this.setValue(currentValue);
  27926. };
  27927. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  27928. if (blend === void 0) { blend = false; }
  27929. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  27930. this._stopped = true;
  27931. return false;
  27932. }
  27933. var returnValue = true;
  27934. // Adding a start key at frame 0 if missing
  27935. if (this._keys[0].frame !== 0) {
  27936. var newKey = { frame: 0, value: this._keys[0].value };
  27937. this._keys.splice(0, 0, newKey);
  27938. }
  27939. // Check limits
  27940. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  27941. from = this._keys[0].frame;
  27942. }
  27943. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  27944. to = this._keys[this._keys.length - 1].frame;
  27945. }
  27946. // Compute ratio
  27947. var range = to - from;
  27948. var offsetValue;
  27949. // ratio represents the frame delta between from and to
  27950. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  27951. var highLimitValue = 0;
  27952. if (ratio > range && !loop) {
  27953. returnValue = false;
  27954. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  27955. }
  27956. else {
  27957. // Get max value if required
  27958. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  27959. var keyOffset = to.toString() + from.toString();
  27960. if (!this._offsetsCache[keyOffset]) {
  27961. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27962. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  27963. switch (this.dataType) {
  27964. // Float
  27965. case Animation.ANIMATIONTYPE_FLOAT:
  27966. this._offsetsCache[keyOffset] = toValue - fromValue;
  27967. break;
  27968. // Quaternion
  27969. case Animation.ANIMATIONTYPE_QUATERNION:
  27970. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27971. break;
  27972. // Vector3
  27973. case Animation.ANIMATIONTYPE_VECTOR3:
  27974. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27975. // Vector2
  27976. case Animation.ANIMATIONTYPE_VECTOR2:
  27977. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27978. // Size
  27979. case Animation.ANIMATIONTYPE_SIZE:
  27980. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27981. // Color3
  27982. case Animation.ANIMATIONTYPE_COLOR3:
  27983. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  27984. default:
  27985. break;
  27986. }
  27987. this._highLimitsCache[keyOffset] = toValue;
  27988. }
  27989. highLimitValue = this._highLimitsCache[keyOffset];
  27990. offsetValue = this._offsetsCache[keyOffset];
  27991. }
  27992. }
  27993. if (offsetValue === undefined) {
  27994. switch (this.dataType) {
  27995. // Float
  27996. case Animation.ANIMATIONTYPE_FLOAT:
  27997. offsetValue = 0;
  27998. break;
  27999. // Quaternion
  28000. case Animation.ANIMATIONTYPE_QUATERNION:
  28001. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28002. break;
  28003. // Vector3
  28004. case Animation.ANIMATIONTYPE_VECTOR3:
  28005. offsetValue = BABYLON.Vector3.Zero();
  28006. break;
  28007. // Vector2
  28008. case Animation.ANIMATIONTYPE_VECTOR2:
  28009. offsetValue = BABYLON.Vector2.Zero();
  28010. break;
  28011. // Size
  28012. case Animation.ANIMATIONTYPE_SIZE:
  28013. offsetValue = BABYLON.Size.Zero();
  28014. break;
  28015. // Color3
  28016. case Animation.ANIMATIONTYPE_COLOR3:
  28017. offsetValue = BABYLON.Color3.Black();
  28018. }
  28019. }
  28020. // Compute value
  28021. var repeatCount = (ratio / range) >> 0;
  28022. var currentFrame = returnValue ? from + ratio % range : to;
  28023. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28024. // Set value
  28025. this.setValue(currentValue);
  28026. // Check events
  28027. for (var index = 0; index < this._events.length; index++) {
  28028. if (currentFrame >= this._events[index].frame) {
  28029. var event = this._events[index];
  28030. if (!event.isDone) {
  28031. // If event should be done only once, remove it.
  28032. if (event.onlyOnce) {
  28033. this._events.splice(index, 1);
  28034. index--;
  28035. }
  28036. event.isDone = true;
  28037. event.action();
  28038. } // Don't do anything if the event has already be done.
  28039. }
  28040. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28041. // reset event, the animation is looping
  28042. this._events[index].isDone = false;
  28043. }
  28044. }
  28045. if (!returnValue) {
  28046. this._stopped = true;
  28047. }
  28048. return returnValue;
  28049. };
  28050. Animation.prototype.serialize = function () {
  28051. var serializationObject = {};
  28052. serializationObject.name = this.name;
  28053. serializationObject.property = this.targetProperty;
  28054. serializationObject.framePerSecond = this.framePerSecond;
  28055. serializationObject.dataType = this.dataType;
  28056. serializationObject.loopBehavior = this.loopMode;
  28057. var dataType = this.dataType;
  28058. serializationObject.keys = [];
  28059. var keys = this.getKeys();
  28060. for (var index = 0; index < keys.length; index++) {
  28061. var animationKey = keys[index];
  28062. var key = {};
  28063. key.frame = animationKey.frame;
  28064. switch (dataType) {
  28065. case Animation.ANIMATIONTYPE_FLOAT:
  28066. key.values = [animationKey.value];
  28067. break;
  28068. case Animation.ANIMATIONTYPE_QUATERNION:
  28069. case Animation.ANIMATIONTYPE_MATRIX:
  28070. case Animation.ANIMATIONTYPE_VECTOR3:
  28071. case Animation.ANIMATIONTYPE_COLOR3:
  28072. key.values = animationKey.value.asArray();
  28073. break;
  28074. }
  28075. serializationObject.keys.push(key);
  28076. }
  28077. serializationObject.ranges = [];
  28078. for (var name in this._ranges) {
  28079. var range = {};
  28080. range.name = name;
  28081. range.from = this._ranges[name].from;
  28082. range.to = this._ranges[name].to;
  28083. serializationObject.ranges.push(range);
  28084. }
  28085. return serializationObject;
  28086. };
  28087. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28088. get: function () {
  28089. return Animation._ANIMATIONTYPE_FLOAT;
  28090. },
  28091. enumerable: true,
  28092. configurable: true
  28093. });
  28094. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28095. get: function () {
  28096. return Animation._ANIMATIONTYPE_VECTOR3;
  28097. },
  28098. enumerable: true,
  28099. configurable: true
  28100. });
  28101. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28102. get: function () {
  28103. return Animation._ANIMATIONTYPE_VECTOR2;
  28104. },
  28105. enumerable: true,
  28106. configurable: true
  28107. });
  28108. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28109. get: function () {
  28110. return Animation._ANIMATIONTYPE_SIZE;
  28111. },
  28112. enumerable: true,
  28113. configurable: true
  28114. });
  28115. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28116. get: function () {
  28117. return Animation._ANIMATIONTYPE_QUATERNION;
  28118. },
  28119. enumerable: true,
  28120. configurable: true
  28121. });
  28122. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28123. get: function () {
  28124. return Animation._ANIMATIONTYPE_MATRIX;
  28125. },
  28126. enumerable: true,
  28127. configurable: true
  28128. });
  28129. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28130. get: function () {
  28131. return Animation._ANIMATIONTYPE_COLOR3;
  28132. },
  28133. enumerable: true,
  28134. configurable: true
  28135. });
  28136. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28137. get: function () {
  28138. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28139. },
  28140. enumerable: true,
  28141. configurable: true
  28142. });
  28143. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28144. get: function () {
  28145. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28146. },
  28147. enumerable: true,
  28148. configurable: true
  28149. });
  28150. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28151. get: function () {
  28152. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28153. },
  28154. enumerable: true,
  28155. configurable: true
  28156. });
  28157. Animation.Parse = function (parsedAnimation) {
  28158. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28159. var dataType = parsedAnimation.dataType;
  28160. var keys = [];
  28161. var data;
  28162. var index;
  28163. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28164. var key = parsedAnimation.keys[index];
  28165. switch (dataType) {
  28166. case Animation.ANIMATIONTYPE_FLOAT:
  28167. data = key.values[0];
  28168. break;
  28169. case Animation.ANIMATIONTYPE_QUATERNION:
  28170. data = BABYLON.Quaternion.FromArray(key.values);
  28171. break;
  28172. case Animation.ANIMATIONTYPE_MATRIX:
  28173. data = BABYLON.Matrix.FromArray(key.values);
  28174. break;
  28175. case Animation.ANIMATIONTYPE_COLOR3:
  28176. data = BABYLON.Color3.FromArray(key.values);
  28177. break;
  28178. case Animation.ANIMATIONTYPE_VECTOR3:
  28179. default:
  28180. data = BABYLON.Vector3.FromArray(key.values);
  28181. break;
  28182. }
  28183. keys.push({
  28184. frame: key.frame,
  28185. value: data
  28186. });
  28187. }
  28188. animation.setKeys(keys);
  28189. if (parsedAnimation.ranges) {
  28190. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  28191. data = parsedAnimation.ranges[index];
  28192. animation.createRange(data.name, data.from, data.to);
  28193. }
  28194. }
  28195. return animation;
  28196. };
  28197. Animation.AppendSerializedAnimations = function (source, destination) {
  28198. if (source.animations) {
  28199. destination.animations = [];
  28200. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  28201. var animation = source.animations[animationIndex];
  28202. destination.animations.push(animation.serialize());
  28203. }
  28204. }
  28205. };
  28206. // Statics
  28207. Animation._ANIMATIONTYPE_FLOAT = 0;
  28208. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  28209. Animation._ANIMATIONTYPE_QUATERNION = 2;
  28210. Animation._ANIMATIONTYPE_MATRIX = 3;
  28211. Animation._ANIMATIONTYPE_COLOR3 = 4;
  28212. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  28213. Animation._ANIMATIONTYPE_SIZE = 6;
  28214. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  28215. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  28216. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  28217. return Animation;
  28218. }());
  28219. BABYLON.Animation = Animation;
  28220. })(BABYLON || (BABYLON = {}));
  28221. var BABYLON;
  28222. (function (BABYLON) {
  28223. var Animatable = (function () {
  28224. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  28225. if (fromFrame === void 0) { fromFrame = 0; }
  28226. if (toFrame === void 0) { toFrame = 100; }
  28227. if (loopAnimation === void 0) { loopAnimation = false; }
  28228. if (speedRatio === void 0) { speedRatio = 1.0; }
  28229. this.target = target;
  28230. this.fromFrame = fromFrame;
  28231. this.toFrame = toFrame;
  28232. this.loopAnimation = loopAnimation;
  28233. this.speedRatio = speedRatio;
  28234. this.onAnimationEnd = onAnimationEnd;
  28235. this._animations = new Array();
  28236. this._paused = false;
  28237. this.animationStarted = false;
  28238. if (animations) {
  28239. this.appendAnimations(target, animations);
  28240. }
  28241. this._scene = scene;
  28242. scene._activeAnimatables.push(this);
  28243. }
  28244. // Methods
  28245. Animatable.prototype.getAnimations = function () {
  28246. return this._animations;
  28247. };
  28248. Animatable.prototype.appendAnimations = function (target, animations) {
  28249. for (var index = 0; index < animations.length; index++) {
  28250. var animation = animations[index];
  28251. animation._target = target;
  28252. this._animations.push(animation);
  28253. }
  28254. };
  28255. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  28256. var animations = this._animations;
  28257. for (var index = 0; index < animations.length; index++) {
  28258. if (animations[index].targetProperty === property) {
  28259. return animations[index];
  28260. }
  28261. }
  28262. return null;
  28263. };
  28264. Animatable.prototype.reset = function () {
  28265. var animations = this._animations;
  28266. for (var index = 0; index < animations.length; index++) {
  28267. animations[index].reset();
  28268. }
  28269. this._localDelayOffset = null;
  28270. this._pausedDelay = null;
  28271. };
  28272. Animatable.prototype.enableBlending = function (blendingSpeed) {
  28273. var animations = this._animations;
  28274. for (var index = 0; index < animations.length; index++) {
  28275. animations[index].enableBlending = true;
  28276. animations[index].blendingSpeed = blendingSpeed;
  28277. }
  28278. };
  28279. Animatable.prototype.disableBlending = function () {
  28280. var animations = this._animations;
  28281. for (var index = 0; index < animations.length; index++) {
  28282. animations[index].enableBlending = false;
  28283. }
  28284. };
  28285. Animatable.prototype.goToFrame = function (frame) {
  28286. var animations = this._animations;
  28287. for (var index = 0; index < animations.length; index++) {
  28288. animations[index].goToFrame(frame);
  28289. }
  28290. };
  28291. Animatable.prototype.pause = function () {
  28292. if (this._paused) {
  28293. return;
  28294. }
  28295. this._paused = true;
  28296. };
  28297. Animatable.prototype.restart = function () {
  28298. this._paused = false;
  28299. };
  28300. Animatable.prototype.stop = function () {
  28301. var index = this._scene._activeAnimatables.indexOf(this);
  28302. if (index > -1) {
  28303. this._scene._activeAnimatables.splice(index, 1);
  28304. var animations = this._animations;
  28305. for (var index = 0; index < animations.length; index++) {
  28306. animations[index].reset();
  28307. }
  28308. if (this.onAnimationEnd) {
  28309. this.onAnimationEnd();
  28310. }
  28311. }
  28312. };
  28313. Animatable.prototype._animate = function (delay) {
  28314. if (this._paused) {
  28315. this.animationStarted = false;
  28316. if (!this._pausedDelay) {
  28317. this._pausedDelay = delay;
  28318. }
  28319. return true;
  28320. }
  28321. if (!this._localDelayOffset) {
  28322. this._localDelayOffset = delay;
  28323. }
  28324. else if (this._pausedDelay) {
  28325. this._localDelayOffset += delay - this._pausedDelay;
  28326. this._pausedDelay = null;
  28327. }
  28328. // Animating
  28329. var running = false;
  28330. var animations = this._animations;
  28331. var index;
  28332. for (index = 0; index < animations.length; index++) {
  28333. var animation = animations[index];
  28334. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  28335. running = running || isRunning;
  28336. }
  28337. this.animationStarted = running;
  28338. if (!running) {
  28339. // Remove from active animatables
  28340. index = this._scene._activeAnimatables.indexOf(this);
  28341. this._scene._activeAnimatables.splice(index, 1);
  28342. }
  28343. if (!running && this.onAnimationEnd) {
  28344. this.onAnimationEnd();
  28345. this.onAnimationEnd = null;
  28346. }
  28347. return running;
  28348. };
  28349. return Animatable;
  28350. }());
  28351. BABYLON.Animatable = Animatable;
  28352. })(BABYLON || (BABYLON = {}));
  28353. var BABYLON;
  28354. (function (BABYLON) {
  28355. var EasingFunction = (function () {
  28356. function EasingFunction() {
  28357. // Properties
  28358. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  28359. }
  28360. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  28361. get: function () {
  28362. return EasingFunction._EASINGMODE_EASEIN;
  28363. },
  28364. enumerable: true,
  28365. configurable: true
  28366. });
  28367. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  28368. get: function () {
  28369. return EasingFunction._EASINGMODE_EASEOUT;
  28370. },
  28371. enumerable: true,
  28372. configurable: true
  28373. });
  28374. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  28375. get: function () {
  28376. return EasingFunction._EASINGMODE_EASEINOUT;
  28377. },
  28378. enumerable: true,
  28379. configurable: true
  28380. });
  28381. EasingFunction.prototype.setEasingMode = function (easingMode) {
  28382. var n = Math.min(Math.max(easingMode, 0), 2);
  28383. this._easingMode = n;
  28384. };
  28385. EasingFunction.prototype.getEasingMode = function () {
  28386. return this._easingMode;
  28387. };
  28388. EasingFunction.prototype.easeInCore = function (gradient) {
  28389. throw new Error('You must implement this method');
  28390. };
  28391. EasingFunction.prototype.ease = function (gradient) {
  28392. switch (this._easingMode) {
  28393. case EasingFunction.EASINGMODE_EASEIN:
  28394. return this.easeInCore(gradient);
  28395. case EasingFunction.EASINGMODE_EASEOUT:
  28396. return (1 - this.easeInCore(1 - gradient));
  28397. }
  28398. if (gradient >= 0.5) {
  28399. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  28400. }
  28401. return (this.easeInCore(gradient * 2) * 0.5);
  28402. };
  28403. //Statics
  28404. EasingFunction._EASINGMODE_EASEIN = 0;
  28405. EasingFunction._EASINGMODE_EASEOUT = 1;
  28406. EasingFunction._EASINGMODE_EASEINOUT = 2;
  28407. return EasingFunction;
  28408. }());
  28409. BABYLON.EasingFunction = EasingFunction;
  28410. var CircleEase = (function (_super) {
  28411. __extends(CircleEase, _super);
  28412. function CircleEase() {
  28413. _super.apply(this, arguments);
  28414. }
  28415. CircleEase.prototype.easeInCore = function (gradient) {
  28416. gradient = Math.max(0, Math.min(1, gradient));
  28417. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  28418. };
  28419. return CircleEase;
  28420. }(EasingFunction));
  28421. BABYLON.CircleEase = CircleEase;
  28422. var BackEase = (function (_super) {
  28423. __extends(BackEase, _super);
  28424. function BackEase(amplitude) {
  28425. if (amplitude === void 0) { amplitude = 1; }
  28426. _super.call(this);
  28427. this.amplitude = amplitude;
  28428. }
  28429. BackEase.prototype.easeInCore = function (gradient) {
  28430. var num = Math.max(0, this.amplitude);
  28431. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  28432. };
  28433. return BackEase;
  28434. }(EasingFunction));
  28435. BABYLON.BackEase = BackEase;
  28436. var BounceEase = (function (_super) {
  28437. __extends(BounceEase, _super);
  28438. function BounceEase(bounces, bounciness) {
  28439. if (bounces === void 0) { bounces = 3; }
  28440. if (bounciness === void 0) { bounciness = 2; }
  28441. _super.call(this);
  28442. this.bounces = bounces;
  28443. this.bounciness = bounciness;
  28444. }
  28445. BounceEase.prototype.easeInCore = function (gradient) {
  28446. var y = Math.max(0.0, this.bounces);
  28447. var bounciness = this.bounciness;
  28448. if (bounciness <= 1.0) {
  28449. bounciness = 1.001;
  28450. }
  28451. var num9 = Math.pow(bounciness, y);
  28452. var num5 = 1.0 - bounciness;
  28453. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  28454. var num15 = gradient * num4;
  28455. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  28456. var num3 = Math.floor(num65);
  28457. var num13 = num3 + 1.0;
  28458. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  28459. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  28460. var num7 = (num8 + num12) * 0.5;
  28461. var num6 = gradient - num7;
  28462. var num2 = num7 - num8;
  28463. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  28464. };
  28465. return BounceEase;
  28466. }(EasingFunction));
  28467. BABYLON.BounceEase = BounceEase;
  28468. var CubicEase = (function (_super) {
  28469. __extends(CubicEase, _super);
  28470. function CubicEase() {
  28471. _super.apply(this, arguments);
  28472. }
  28473. CubicEase.prototype.easeInCore = function (gradient) {
  28474. return (gradient * gradient * gradient);
  28475. };
  28476. return CubicEase;
  28477. }(EasingFunction));
  28478. BABYLON.CubicEase = CubicEase;
  28479. var ElasticEase = (function (_super) {
  28480. __extends(ElasticEase, _super);
  28481. function ElasticEase(oscillations, springiness) {
  28482. if (oscillations === void 0) { oscillations = 3; }
  28483. if (springiness === void 0) { springiness = 3; }
  28484. _super.call(this);
  28485. this.oscillations = oscillations;
  28486. this.springiness = springiness;
  28487. }
  28488. ElasticEase.prototype.easeInCore = function (gradient) {
  28489. var num2;
  28490. var num3 = Math.max(0.0, this.oscillations);
  28491. var num = Math.max(0.0, this.springiness);
  28492. if (num == 0) {
  28493. num2 = gradient;
  28494. }
  28495. else {
  28496. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  28497. }
  28498. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  28499. };
  28500. return ElasticEase;
  28501. }(EasingFunction));
  28502. BABYLON.ElasticEase = ElasticEase;
  28503. var ExponentialEase = (function (_super) {
  28504. __extends(ExponentialEase, _super);
  28505. function ExponentialEase(exponent) {
  28506. if (exponent === void 0) { exponent = 2; }
  28507. _super.call(this);
  28508. this.exponent = exponent;
  28509. }
  28510. ExponentialEase.prototype.easeInCore = function (gradient) {
  28511. if (this.exponent <= 0) {
  28512. return gradient;
  28513. }
  28514. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  28515. };
  28516. return ExponentialEase;
  28517. }(EasingFunction));
  28518. BABYLON.ExponentialEase = ExponentialEase;
  28519. var PowerEase = (function (_super) {
  28520. __extends(PowerEase, _super);
  28521. function PowerEase(power) {
  28522. if (power === void 0) { power = 2; }
  28523. _super.call(this);
  28524. this.power = power;
  28525. }
  28526. PowerEase.prototype.easeInCore = function (gradient) {
  28527. var y = Math.max(0.0, this.power);
  28528. return Math.pow(gradient, y);
  28529. };
  28530. return PowerEase;
  28531. }(EasingFunction));
  28532. BABYLON.PowerEase = PowerEase;
  28533. var QuadraticEase = (function (_super) {
  28534. __extends(QuadraticEase, _super);
  28535. function QuadraticEase() {
  28536. _super.apply(this, arguments);
  28537. }
  28538. QuadraticEase.prototype.easeInCore = function (gradient) {
  28539. return (gradient * gradient);
  28540. };
  28541. return QuadraticEase;
  28542. }(EasingFunction));
  28543. BABYLON.QuadraticEase = QuadraticEase;
  28544. var QuarticEase = (function (_super) {
  28545. __extends(QuarticEase, _super);
  28546. function QuarticEase() {
  28547. _super.apply(this, arguments);
  28548. }
  28549. QuarticEase.prototype.easeInCore = function (gradient) {
  28550. return (gradient * gradient * gradient * gradient);
  28551. };
  28552. return QuarticEase;
  28553. }(EasingFunction));
  28554. BABYLON.QuarticEase = QuarticEase;
  28555. var QuinticEase = (function (_super) {
  28556. __extends(QuinticEase, _super);
  28557. function QuinticEase() {
  28558. _super.apply(this, arguments);
  28559. }
  28560. QuinticEase.prototype.easeInCore = function (gradient) {
  28561. return (gradient * gradient * gradient * gradient * gradient);
  28562. };
  28563. return QuinticEase;
  28564. }(EasingFunction));
  28565. BABYLON.QuinticEase = QuinticEase;
  28566. var SineEase = (function (_super) {
  28567. __extends(SineEase, _super);
  28568. function SineEase() {
  28569. _super.apply(this, arguments);
  28570. }
  28571. SineEase.prototype.easeInCore = function (gradient) {
  28572. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  28573. };
  28574. return SineEase;
  28575. }(EasingFunction));
  28576. BABYLON.SineEase = SineEase;
  28577. var BezierCurveEase = (function (_super) {
  28578. __extends(BezierCurveEase, _super);
  28579. function BezierCurveEase(x1, y1, x2, y2) {
  28580. if (x1 === void 0) { x1 = 0; }
  28581. if (y1 === void 0) { y1 = 0; }
  28582. if (x2 === void 0) { x2 = 1; }
  28583. if (y2 === void 0) { y2 = 1; }
  28584. _super.call(this);
  28585. this.x1 = x1;
  28586. this.y1 = y1;
  28587. this.x2 = x2;
  28588. this.y2 = y2;
  28589. }
  28590. BezierCurveEase.prototype.easeInCore = function (gradient) {
  28591. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  28592. };
  28593. return BezierCurveEase;
  28594. }(EasingFunction));
  28595. BABYLON.BezierCurveEase = BezierCurveEase;
  28596. })(BABYLON || (BABYLON = {}));
  28597. var BABYLON;
  28598. (function (BABYLON) {
  28599. var Bone = (function (_super) {
  28600. __extends(Bone, _super);
  28601. function Bone(name, skeleton, parentBone, matrix, restPose) {
  28602. _super.call(this, name, skeleton.getScene());
  28603. this.name = name;
  28604. this.children = new Array();
  28605. this.animations = new Array();
  28606. this._worldTransform = new BABYLON.Matrix();
  28607. this._absoluteTransform = new BABYLON.Matrix();
  28608. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  28609. this._skeleton = skeleton;
  28610. this._matrix = matrix;
  28611. this._baseMatrix = matrix;
  28612. this._restPose = restPose ? restPose : matrix.clone();
  28613. skeleton.bones.push(this);
  28614. if (parentBone) {
  28615. this._parent = parentBone;
  28616. parentBone.children.push(this);
  28617. }
  28618. else {
  28619. this._parent = null;
  28620. }
  28621. this._updateDifferenceMatrix();
  28622. }
  28623. // Members
  28624. Bone.prototype.getParent = function () {
  28625. return this._parent;
  28626. };
  28627. Bone.prototype.getLocalMatrix = function () {
  28628. return this._matrix;
  28629. };
  28630. Bone.prototype.getBaseMatrix = function () {
  28631. return this._baseMatrix;
  28632. };
  28633. Bone.prototype.getRestPose = function () {
  28634. return this._restPose;
  28635. };
  28636. Bone.prototype.returnToRest = function () {
  28637. this.updateMatrix(this._restPose.clone());
  28638. };
  28639. Bone.prototype.getWorldMatrix = function () {
  28640. return this._worldTransform;
  28641. };
  28642. Bone.prototype.getInvertedAbsoluteTransform = function () {
  28643. return this._invertedAbsoluteTransform;
  28644. };
  28645. Bone.prototype.getAbsoluteTransform = function () {
  28646. return this._absoluteTransform;
  28647. };
  28648. // Methods
  28649. Bone.prototype.updateMatrix = function (matrix) {
  28650. this._baseMatrix = matrix.clone();
  28651. this._matrix = matrix.clone();
  28652. this._skeleton._markAsDirty();
  28653. this._updateDifferenceMatrix();
  28654. };
  28655. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  28656. if (!rootMatrix) {
  28657. rootMatrix = this._baseMatrix;
  28658. }
  28659. if (this._parent) {
  28660. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  28661. }
  28662. else {
  28663. this._absoluteTransform.copyFrom(rootMatrix);
  28664. }
  28665. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  28666. for (var index = 0; index < this.children.length; index++) {
  28667. this.children[index]._updateDifferenceMatrix();
  28668. }
  28669. };
  28670. Bone.prototype.markAsDirty = function () {
  28671. this._currentRenderId++;
  28672. this._skeleton._markAsDirty();
  28673. };
  28674. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  28675. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28676. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  28677. // all animation may be coming from a library skeleton, so may need to create animation
  28678. if (this.animations.length === 0) {
  28679. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  28680. this.animations[0].setKeys([]);
  28681. }
  28682. // get animation info / verify there is such a range from the source bone
  28683. var sourceRange = source.animations[0].getRange(rangeName);
  28684. if (!sourceRange) {
  28685. return false;
  28686. }
  28687. var from = sourceRange.from;
  28688. var to = sourceRange.to;
  28689. var sourceKeys = source.animations[0].getKeys();
  28690. // rescaling prep
  28691. var sourceBoneLength = source.length;
  28692. var sourceParent = source.getParent();
  28693. var parent = this.getParent();
  28694. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  28695. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  28696. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  28697. var destKeys = this.animations[0].getKeys();
  28698. // loop vars declaration
  28699. var orig;
  28700. var origTranslation;
  28701. var mat;
  28702. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  28703. orig = sourceKeys[key];
  28704. if (orig.frame >= from && orig.frame <= to) {
  28705. if (rescaleAsRequired) {
  28706. mat = orig.value.clone();
  28707. // scale based on parent ratio, when bone has parent
  28708. if (parentScalingReqd) {
  28709. origTranslation = mat.getTranslation();
  28710. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  28711. }
  28712. else if (dimensionsScalingReqd) {
  28713. origTranslation = mat.getTranslation();
  28714. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  28715. }
  28716. else {
  28717. mat = orig.value;
  28718. }
  28719. }
  28720. else {
  28721. mat = orig.value;
  28722. }
  28723. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  28724. }
  28725. }
  28726. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  28727. return true;
  28728. };
  28729. return Bone;
  28730. }(BABYLON.Node));
  28731. BABYLON.Bone = Bone;
  28732. })(BABYLON || (BABYLON = {}));
  28733. var BABYLON;
  28734. (function (BABYLON) {
  28735. var Skeleton = (function () {
  28736. function Skeleton(name, id, scene) {
  28737. this.name = name;
  28738. this.id = id;
  28739. this.bones = new Array();
  28740. this.needInitialSkinMatrix = false;
  28741. this._isDirty = true;
  28742. this._meshesWithPoseMatrix = new Array();
  28743. this._identity = BABYLON.Matrix.Identity();
  28744. this._ranges = {};
  28745. this.bones = [];
  28746. this._scene = scene;
  28747. scene.skeletons.push(this);
  28748. //make sure it will recalculate the matrix next time prepare is called.
  28749. this._isDirty = true;
  28750. }
  28751. // Members
  28752. Skeleton.prototype.getTransformMatrices = function (mesh) {
  28753. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  28754. return mesh._bonesTransformMatrices;
  28755. }
  28756. return this._transformMatrices;
  28757. };
  28758. Skeleton.prototype.getScene = function () {
  28759. return this._scene;
  28760. };
  28761. // Methods
  28762. /**
  28763. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28764. */
  28765. Skeleton.prototype.toString = function (fullDetails) {
  28766. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  28767. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28768. if (fullDetails) {
  28769. ret += ", Ranges: {";
  28770. var first = true;
  28771. for (var name_1 in this._ranges) {
  28772. if (first) {
  28773. ret += ", ";
  28774. first = false;
  28775. }
  28776. ret += name_1;
  28777. }
  28778. ret += "}";
  28779. }
  28780. return ret;
  28781. };
  28782. /**
  28783. * Get bone's index searching by name
  28784. * @param {string} name is bone's name to search for
  28785. * @return {number} Indice of the bone. Returns -1 if not found
  28786. */
  28787. Skeleton.prototype.getBoneIndexByName = function (name) {
  28788. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  28789. if (this.bones[boneIndex].name === name) {
  28790. return boneIndex;
  28791. }
  28792. }
  28793. return -1;
  28794. };
  28795. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  28796. // check name not already in use
  28797. if (!this._ranges[name]) {
  28798. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  28799. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28800. if (this.bones[i].animations[0]) {
  28801. this.bones[i].animations[0].createRange(name, from, to);
  28802. }
  28803. }
  28804. }
  28805. };
  28806. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  28807. if (deleteFrames === void 0) { deleteFrames = true; }
  28808. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28809. if (this.bones[i].animations[0]) {
  28810. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  28811. }
  28812. }
  28813. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28814. };
  28815. Skeleton.prototype.getAnimationRange = function (name) {
  28816. return this._ranges[name];
  28817. };
  28818. /**
  28819. * Returns as an Array, all AnimationRanges defined on this skeleton
  28820. */
  28821. Skeleton.prototype.getAnimationRanges = function () {
  28822. var animationRanges = [];
  28823. var name;
  28824. var i = 0;
  28825. for (name in this._ranges) {
  28826. animationRanges[i] = this._ranges[name];
  28827. i++;
  28828. }
  28829. return animationRanges;
  28830. };
  28831. /**
  28832. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  28833. */
  28834. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  28835. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  28836. if (this._ranges[name] || !source.getAnimationRange(name)) {
  28837. return false;
  28838. }
  28839. var ret = true;
  28840. var frameOffset = this._getHighestAnimationFrame() + 1;
  28841. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  28842. var boneDict = {};
  28843. var sourceBones = source.bones;
  28844. var nBones;
  28845. var i;
  28846. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  28847. boneDict[sourceBones[i].name] = sourceBones[i];
  28848. }
  28849. if (this.bones.length !== sourceBones.length) {
  28850. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  28851. ret = false;
  28852. }
  28853. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  28854. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  28855. var boneName = this.bones[i].name;
  28856. var sourceBone = boneDict[boneName];
  28857. if (sourceBone) {
  28858. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  28859. }
  28860. else {
  28861. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  28862. ret = false;
  28863. }
  28864. }
  28865. // do not call createAnimationRange(), since it also is done to bones, which was already done
  28866. var range = source.getAnimationRange(name);
  28867. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  28868. return ret;
  28869. };
  28870. Skeleton.prototype.returnToRest = function () {
  28871. for (var index = 0; index < this.bones.length; index++) {
  28872. this.bones[index].returnToRest();
  28873. }
  28874. };
  28875. Skeleton.prototype._getHighestAnimationFrame = function () {
  28876. var ret = 0;
  28877. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  28878. if (this.bones[i].animations[0]) {
  28879. var highest = this.bones[i].animations[0].getHighestFrame();
  28880. if (ret < highest) {
  28881. ret = highest;
  28882. }
  28883. }
  28884. }
  28885. return ret;
  28886. };
  28887. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  28888. var range = this.getAnimationRange(name);
  28889. if (!range) {
  28890. return null;
  28891. }
  28892. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  28893. };
  28894. Skeleton.prototype._markAsDirty = function () {
  28895. this._isDirty = true;
  28896. };
  28897. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  28898. this._meshesWithPoseMatrix.push(mesh);
  28899. };
  28900. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  28901. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  28902. if (index > -1) {
  28903. this._meshesWithPoseMatrix.splice(index, 1);
  28904. }
  28905. };
  28906. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  28907. for (var index = 0; index < this.bones.length; index++) {
  28908. var bone = this.bones[index];
  28909. var parentBone = bone.getParent();
  28910. if (parentBone) {
  28911. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  28912. }
  28913. else {
  28914. if (initialSkinMatrix) {
  28915. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  28916. }
  28917. else {
  28918. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  28919. }
  28920. }
  28921. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  28922. }
  28923. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  28924. };
  28925. Skeleton.prototype.prepare = function () {
  28926. if (!this._isDirty) {
  28927. return;
  28928. }
  28929. if (this.needInitialSkinMatrix) {
  28930. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  28931. var mesh = this._meshesWithPoseMatrix[index];
  28932. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  28933. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28934. }
  28935. var poseMatrix = mesh.getPoseMatrix();
  28936. // Prepare bones
  28937. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  28938. var bone = this.bones[boneIndex];
  28939. if (!bone.getParent()) {
  28940. var matrix = bone.getBaseMatrix();
  28941. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  28942. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  28943. }
  28944. }
  28945. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  28946. }
  28947. }
  28948. else {
  28949. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  28950. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  28951. }
  28952. this._computeTransformMatrices(this._transformMatrices, null);
  28953. }
  28954. this._isDirty = false;
  28955. this._scene._activeBones.addCount(this.bones.length, false);
  28956. };
  28957. Skeleton.prototype.getAnimatables = function () {
  28958. if (!this._animatables || this._animatables.length !== this.bones.length) {
  28959. this._animatables = [];
  28960. for (var index = 0; index < this.bones.length; index++) {
  28961. this._animatables.push(this.bones[index]);
  28962. }
  28963. }
  28964. return this._animatables;
  28965. };
  28966. Skeleton.prototype.clone = function (name, id) {
  28967. var result = new Skeleton(name, id || name, this._scene);
  28968. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  28969. for (var index = 0; index < this.bones.length; index++) {
  28970. var source = this.bones[index];
  28971. var parentBone = null;
  28972. if (source.getParent()) {
  28973. var parentIndex = this.bones.indexOf(source.getParent());
  28974. parentBone = result.bones[parentIndex];
  28975. }
  28976. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  28977. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  28978. }
  28979. if (this._ranges) {
  28980. result._ranges = {};
  28981. for (var rangeName in this._ranges) {
  28982. result._ranges[rangeName] = this._ranges[rangeName].clone();
  28983. }
  28984. }
  28985. this._isDirty = true;
  28986. return result;
  28987. };
  28988. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  28989. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  28990. this.bones.forEach(function (bone) {
  28991. bone.animations.forEach(function (animation) {
  28992. animation.enableBlending = true;
  28993. animation.blendingSpeed = blendingSpeed;
  28994. });
  28995. });
  28996. };
  28997. Skeleton.prototype.dispose = function () {
  28998. this._meshesWithPoseMatrix = [];
  28999. // Animations
  29000. this.getScene().stopAnimation(this);
  29001. // Remove from scene
  29002. this.getScene().removeSkeleton(this);
  29003. };
  29004. Skeleton.prototype.serialize = function () {
  29005. var serializationObject = {};
  29006. serializationObject.name = this.name;
  29007. serializationObject.id = this.id;
  29008. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  29009. serializationObject.bones = [];
  29010. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  29011. for (var index = 0; index < this.bones.length; index++) {
  29012. var bone = this.bones[index];
  29013. var serializedBone = {
  29014. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  29015. name: bone.name,
  29016. matrix: bone.getLocalMatrix().toArray(),
  29017. rest: bone.getRestPose().toArray()
  29018. };
  29019. serializationObject.bones.push(serializedBone);
  29020. if (bone.length) {
  29021. serializedBone.length = bone.length;
  29022. }
  29023. if (bone.animations && bone.animations.length > 0) {
  29024. serializedBone.animation = bone.animations[0].serialize();
  29025. }
  29026. serializationObject.ranges = [];
  29027. for (var name in this._ranges) {
  29028. var range = {};
  29029. range.name = name;
  29030. range.from = this._ranges[name].from;
  29031. range.to = this._ranges[name].to;
  29032. serializationObject.ranges.push(range);
  29033. }
  29034. }
  29035. return serializationObject;
  29036. };
  29037. Skeleton.Parse = function (parsedSkeleton, scene) {
  29038. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  29039. if (parsedSkeleton.dimensionsAtRest) {
  29040. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  29041. }
  29042. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  29043. var index;
  29044. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  29045. var parsedBone = parsedSkeleton.bones[index];
  29046. var parentBone = null;
  29047. if (parsedBone.parentBoneIndex > -1) {
  29048. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  29049. }
  29050. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  29051. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  29052. if (parsedBone.length) {
  29053. bone.length = parsedBone.length;
  29054. }
  29055. if (parsedBone.animation) {
  29056. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  29057. }
  29058. }
  29059. // placed after bones, so createAnimationRange can cascade down
  29060. if (parsedSkeleton.ranges) {
  29061. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  29062. var data = parsedSkeleton.ranges[index];
  29063. skeleton.createAnimationRange(data.name, data.from, data.to);
  29064. }
  29065. }
  29066. return skeleton;
  29067. };
  29068. return Skeleton;
  29069. }());
  29070. BABYLON.Skeleton = Skeleton;
  29071. })(BABYLON || (BABYLON = {}));
  29072. var BABYLON;
  29073. (function (BABYLON) {
  29074. var PostProcess = (function () {
  29075. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  29076. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  29077. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  29078. this.name = name;
  29079. this.width = -1;
  29080. this.height = -1;
  29081. /*
  29082. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  29083. Can only be used on a single postprocess or on the last one of a chain.
  29084. */
  29085. this.enablePixelPerfectMode = false;
  29086. this._reusable = false;
  29087. this._textures = new BABYLON.SmartArray(2);
  29088. this._currentRenderTextureInd = 0;
  29089. this._scaleRatio = new BABYLON.Vector2(1, 1);
  29090. // Events
  29091. /**
  29092. * An event triggered when the postprocess is activated.
  29093. * @type {BABYLON.Observable}
  29094. */
  29095. this.onActivateObservable = new BABYLON.Observable();
  29096. /**
  29097. * An event triggered when the postprocess changes its size.
  29098. * @type {BABYLON.Observable}
  29099. */
  29100. this.onSizeChangedObservable = new BABYLON.Observable();
  29101. /**
  29102. * An event triggered when the postprocess applies its effect.
  29103. * @type {BABYLON.Observable}
  29104. */
  29105. this.onApplyObservable = new BABYLON.Observable();
  29106. /**
  29107. * An event triggered before rendering the postprocess
  29108. * @type {BABYLON.Observable}
  29109. */
  29110. this.onBeforeRenderObservable = new BABYLON.Observable();
  29111. /**
  29112. * An event triggered after rendering the postprocess
  29113. * @type {BABYLON.Observable}
  29114. */
  29115. this.onAfterRenderObservable = new BABYLON.Observable();
  29116. if (camera != null) {
  29117. this._camera = camera;
  29118. this._scene = camera.getScene();
  29119. camera.attachPostProcess(this);
  29120. this._engine = this._scene.getEngine();
  29121. }
  29122. else {
  29123. this._engine = engine;
  29124. }
  29125. this._options = options;
  29126. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  29127. this._reusable = reusable || false;
  29128. this._textureType = textureType;
  29129. this._samplers = samplers || [];
  29130. this._samplers.push("textureSampler");
  29131. this._fragmentUrl = fragmentUrl;
  29132. this._parameters = parameters || [];
  29133. this._parameters.push("scale");
  29134. this.updateEffect(defines);
  29135. }
  29136. Object.defineProperty(PostProcess.prototype, "onActivate", {
  29137. set: function (callback) {
  29138. if (this._onActivateObserver) {
  29139. this.onActivateObservable.remove(this._onActivateObserver);
  29140. }
  29141. this._onActivateObserver = this.onActivateObservable.add(callback);
  29142. },
  29143. enumerable: true,
  29144. configurable: true
  29145. });
  29146. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  29147. set: function (callback) {
  29148. if (this._onSizeChangedObserver) {
  29149. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  29150. }
  29151. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  29152. },
  29153. enumerable: true,
  29154. configurable: true
  29155. });
  29156. Object.defineProperty(PostProcess.prototype, "onApply", {
  29157. set: function (callback) {
  29158. if (this._onApplyObserver) {
  29159. this.onApplyObservable.remove(this._onApplyObserver);
  29160. }
  29161. this._onApplyObserver = this.onApplyObservable.add(callback);
  29162. },
  29163. enumerable: true,
  29164. configurable: true
  29165. });
  29166. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  29167. set: function (callback) {
  29168. if (this._onBeforeRenderObserver) {
  29169. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29170. }
  29171. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29172. },
  29173. enumerable: true,
  29174. configurable: true
  29175. });
  29176. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  29177. set: function (callback) {
  29178. if (this._onAfterRenderObserver) {
  29179. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29180. }
  29181. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29182. },
  29183. enumerable: true,
  29184. configurable: true
  29185. });
  29186. PostProcess.prototype.updateEffect = function (defines) {
  29187. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  29188. };
  29189. PostProcess.prototype.isReusable = function () {
  29190. return this._reusable;
  29191. };
  29192. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  29193. PostProcess.prototype.markTextureDirty = function () {
  29194. this.width = -1;
  29195. };
  29196. PostProcess.prototype.activate = function (camera, sourceTexture) {
  29197. camera = camera || this._camera;
  29198. var scene = camera.getScene();
  29199. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  29200. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  29201. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  29202. var desiredWidth = this._options.width || requiredWidth;
  29203. var desiredHeight = this._options.height || requiredHeight;
  29204. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  29205. if (!this._options.width) {
  29206. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  29207. }
  29208. if (!this._options.height) {
  29209. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  29210. }
  29211. }
  29212. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  29213. if (this._textures.length > 0) {
  29214. for (var i = 0; i < this._textures.length; i++) {
  29215. this._engine._releaseTexture(this._textures.data[i]);
  29216. }
  29217. this._textures.reset();
  29218. }
  29219. this.width = desiredWidth;
  29220. this.height = desiredHeight;
  29221. var textureSize = { width: this.width, height: this.height };
  29222. var textureOptions = {
  29223. generateMipMaps: false,
  29224. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  29225. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  29226. samplingMode: this.renderTargetSamplingMode,
  29227. type: this._textureType
  29228. };
  29229. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29230. if (this._reusable) {
  29231. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  29232. }
  29233. this.onSizeChangedObservable.notifyObservers(this);
  29234. }
  29235. if (this.enablePixelPerfectMode) {
  29236. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  29237. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  29238. }
  29239. else {
  29240. this._scaleRatio.copyFromFloats(1, 1);
  29241. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  29242. }
  29243. this.onActivateObservable.notifyObservers(camera);
  29244. // Clear
  29245. if (this.clearColor) {
  29246. this._engine.clear(this.clearColor, true, true, true);
  29247. }
  29248. else {
  29249. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  29250. }
  29251. if (this._reusable) {
  29252. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  29253. }
  29254. };
  29255. Object.defineProperty(PostProcess.prototype, "isSupported", {
  29256. get: function () {
  29257. return this._effect.isSupported;
  29258. },
  29259. enumerable: true,
  29260. configurable: true
  29261. });
  29262. PostProcess.prototype.apply = function () {
  29263. // Check
  29264. if (!this._effect.isReady())
  29265. return null;
  29266. // States
  29267. this._engine.enableEffect(this._effect);
  29268. this._engine.setState(false);
  29269. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29270. this._engine.setDepthBuffer(false);
  29271. this._engine.setDepthWrite(false);
  29272. // Texture
  29273. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  29274. // Parameters
  29275. this._effect.setVector2("scale", this._scaleRatio);
  29276. this.onApplyObservable.notifyObservers(this._effect);
  29277. return this._effect;
  29278. };
  29279. PostProcess.prototype.dispose = function (camera) {
  29280. camera = camera || this._camera;
  29281. if (this._textures.length > 0) {
  29282. for (var i = 0; i < this._textures.length; i++) {
  29283. this._engine._releaseTexture(this._textures.data[i]);
  29284. }
  29285. this._textures.reset();
  29286. }
  29287. if (!camera) {
  29288. return;
  29289. }
  29290. camera.detachPostProcess(this);
  29291. var index = camera._postProcesses.indexOf(this);
  29292. if (index === 0 && camera._postProcesses.length > 0) {
  29293. this._camera._postProcesses[0].markTextureDirty();
  29294. }
  29295. this.onActivateObservable.clear();
  29296. this.onAfterRenderObservable.clear();
  29297. this.onApplyObservable.clear();
  29298. this.onBeforeRenderObservable.clear();
  29299. this.onSizeChangedObservable.clear();
  29300. };
  29301. return PostProcess;
  29302. }());
  29303. BABYLON.PostProcess = PostProcess;
  29304. })(BABYLON || (BABYLON = {}));
  29305. var BABYLON;
  29306. (function (BABYLON) {
  29307. var PostProcessManager = (function () {
  29308. function PostProcessManager(scene) {
  29309. this._vertexBuffers = {};
  29310. this._scene = scene;
  29311. }
  29312. PostProcessManager.prototype._prepareBuffers = function () {
  29313. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29314. return;
  29315. }
  29316. // VBO
  29317. var vertices = [];
  29318. vertices.push(1, 1);
  29319. vertices.push(-1, 1);
  29320. vertices.push(-1, -1);
  29321. vertices.push(1, -1);
  29322. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29323. // Indices
  29324. var indices = [];
  29325. indices.push(0);
  29326. indices.push(1);
  29327. indices.push(2);
  29328. indices.push(0);
  29329. indices.push(2);
  29330. indices.push(3);
  29331. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29332. };
  29333. // Methods
  29334. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  29335. var postProcesses = this._scene.activeCamera._postProcesses;
  29336. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29337. return false;
  29338. }
  29339. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  29340. return true;
  29341. };
  29342. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  29343. var engine = this._scene.getEngine();
  29344. for (var index = 0; index < postProcesses.length; index++) {
  29345. if (index < postProcesses.length - 1) {
  29346. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29347. }
  29348. else {
  29349. if (targetTexture) {
  29350. engine.bindFramebuffer(targetTexture);
  29351. }
  29352. else {
  29353. engine.restoreDefaultFramebuffer();
  29354. }
  29355. }
  29356. var pp = postProcesses[index];
  29357. var effect = pp.apply();
  29358. if (effect) {
  29359. pp.onBeforeRenderObservable.notifyObservers(effect);
  29360. // VBOs
  29361. this._prepareBuffers();
  29362. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29363. // Draw order
  29364. engine.draw(true, 0, 6);
  29365. pp.onAfterRenderObservable.notifyObservers(effect);
  29366. }
  29367. }
  29368. // Restore depth buffer
  29369. engine.setDepthBuffer(true);
  29370. engine.setDepthWrite(true);
  29371. };
  29372. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29373. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29374. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29375. return;
  29376. }
  29377. var engine = this._scene.getEngine();
  29378. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29379. if (index < len - 1) {
  29380. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29381. }
  29382. else {
  29383. if (targetTexture) {
  29384. engine.bindFramebuffer(targetTexture, faceIndex);
  29385. }
  29386. else {
  29387. engine.restoreDefaultFramebuffer();
  29388. }
  29389. }
  29390. if (doNotPresent) {
  29391. break;
  29392. }
  29393. var pp = postProcesses[index];
  29394. var effect = pp.apply();
  29395. if (effect) {
  29396. pp.onBeforeRenderObservable.notifyObservers(effect);
  29397. // VBOs
  29398. this._prepareBuffers();
  29399. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29400. // Draw order
  29401. engine.draw(true, 0, 6);
  29402. pp.onAfterRenderObservable.notifyObservers(effect);
  29403. }
  29404. }
  29405. // Restore depth buffer
  29406. engine.setDepthBuffer(true);
  29407. engine.setDepthWrite(true);
  29408. };
  29409. PostProcessManager.prototype.dispose = function () {
  29410. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29411. if (buffer) {
  29412. buffer.dispose();
  29413. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29414. }
  29415. if (this._indexBuffer) {
  29416. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29417. this._indexBuffer = null;
  29418. }
  29419. };
  29420. return PostProcessManager;
  29421. }());
  29422. BABYLON.PostProcessManager = PostProcessManager;
  29423. })(BABYLON || (BABYLON = {}));
  29424. var BABYLON;
  29425. (function (BABYLON) {
  29426. var PassPostProcess = (function (_super) {
  29427. __extends(PassPostProcess, _super);
  29428. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  29429. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  29430. }
  29431. return PassPostProcess;
  29432. }(BABYLON.PostProcess));
  29433. BABYLON.PassPostProcess = PassPostProcess;
  29434. })(BABYLON || (BABYLON = {}));
  29435. var BABYLON;
  29436. (function (BABYLON) {
  29437. /**
  29438. * This is a holder class for the physics joint created by the physics plugin.
  29439. * It holds a set of functions to control the underlying joint.
  29440. */
  29441. var PhysicsJoint = (function () {
  29442. function PhysicsJoint(type, jointData) {
  29443. this.type = type;
  29444. this.jointData = jointData;
  29445. jointData.nativeParams = jointData.nativeParams || {};
  29446. }
  29447. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  29448. get: function () {
  29449. return this._physicsJoint;
  29450. },
  29451. set: function (newJoint) {
  29452. if (this._physicsJoint) {
  29453. }
  29454. this._physicsJoint = newJoint;
  29455. },
  29456. enumerable: true,
  29457. configurable: true
  29458. });
  29459. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  29460. set: function (physicsPlugin) {
  29461. this._physicsPlugin = physicsPlugin;
  29462. },
  29463. enumerable: true,
  29464. configurable: true
  29465. });
  29466. /**
  29467. * Execute a function that is physics-plugin specific.
  29468. * @param {Function} func the function that will be executed.
  29469. * It accepts two parameters: the physics world and the physics joint.
  29470. */
  29471. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  29472. func(this._physicsPlugin.world, this._physicsJoint);
  29473. };
  29474. //TODO check if the native joints are the same
  29475. //Joint Types
  29476. PhysicsJoint.DistanceJoint = 0;
  29477. PhysicsJoint.HingeJoint = 1;
  29478. PhysicsJoint.BallAndSocketJoint = 2;
  29479. PhysicsJoint.WheelJoint = 3;
  29480. PhysicsJoint.SliderJoint = 4;
  29481. //OIMO
  29482. PhysicsJoint.PrismaticJoint = 5;
  29483. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  29484. PhysicsJoint.UniversalJoint = 6;
  29485. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  29486. //Cannon
  29487. //Similar to a Ball-Joint. Different in params
  29488. PhysicsJoint.PointToPointJoint = 8;
  29489. //Cannon only at the moment
  29490. PhysicsJoint.SpringJoint = 9;
  29491. PhysicsJoint.LockJoint = 10;
  29492. return PhysicsJoint;
  29493. }());
  29494. BABYLON.PhysicsJoint = PhysicsJoint;
  29495. /**
  29496. * A class representing a physics distance joint.
  29497. */
  29498. var DistanceJoint = (function (_super) {
  29499. __extends(DistanceJoint, _super);
  29500. function DistanceJoint(jointData) {
  29501. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  29502. }
  29503. /**
  29504. * Update the predefined distance.
  29505. */
  29506. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  29507. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  29508. };
  29509. return DistanceJoint;
  29510. }(PhysicsJoint));
  29511. BABYLON.DistanceJoint = DistanceJoint;
  29512. var MotorEnabledJoint = (function (_super) {
  29513. __extends(MotorEnabledJoint, _super);
  29514. function MotorEnabledJoint(type, jointData) {
  29515. _super.call(this, type, jointData);
  29516. }
  29517. /**
  29518. * Set the motor values.
  29519. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29520. * @param {number} force the force to apply
  29521. * @param {number} maxForce max force for this motor.
  29522. */
  29523. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  29524. this._physicsPlugin.setMotor(this, force, maxForce);
  29525. };
  29526. /**
  29527. * Set the motor's limits.
  29528. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29529. */
  29530. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29531. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29532. };
  29533. return MotorEnabledJoint;
  29534. }(PhysicsJoint));
  29535. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  29536. /**
  29537. * This class represents a single hinge physics joint
  29538. */
  29539. var HingeJoint = (function (_super) {
  29540. __extends(HingeJoint, _super);
  29541. function HingeJoint(jointData) {
  29542. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  29543. }
  29544. /**
  29545. * Set the motor values.
  29546. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29547. * @param {number} force the force to apply
  29548. * @param {number} maxForce max force for this motor.
  29549. */
  29550. HingeJoint.prototype.setMotor = function (force, maxForce) {
  29551. this._physicsPlugin.setMotor(this, force, maxForce);
  29552. };
  29553. /**
  29554. * Set the motor's limits.
  29555. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29556. */
  29557. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  29558. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  29559. };
  29560. return HingeJoint;
  29561. }(MotorEnabledJoint));
  29562. BABYLON.HingeJoint = HingeJoint;
  29563. /**
  29564. * This class represents a dual hinge physics joint (same as wheel joint)
  29565. */
  29566. var Hinge2Joint = (function (_super) {
  29567. __extends(Hinge2Joint, _super);
  29568. function Hinge2Joint(jointData) {
  29569. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  29570. }
  29571. /**
  29572. * Set the motor values.
  29573. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29574. * @param {number} force the force to apply
  29575. * @param {number} maxForce max force for this motor.
  29576. * @param {motorIndex} the motor's index, 0 or 1.
  29577. */
  29578. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  29579. if (motorIndex === void 0) { motorIndex = 0; }
  29580. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  29581. };
  29582. /**
  29583. * Set the motor limits.
  29584. * Attention, this function is plugin specific. Engines won't react 100% the same.
  29585. * @param {number} upperLimit the upper limit
  29586. * @param {number} lowerLimit lower limit
  29587. * @param {motorIndex} the motor's index, 0 or 1.
  29588. */
  29589. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  29590. if (motorIndex === void 0) { motorIndex = 0; }
  29591. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  29592. };
  29593. return Hinge2Joint;
  29594. }(MotorEnabledJoint));
  29595. BABYLON.Hinge2Joint = Hinge2Joint;
  29596. })(BABYLON || (BABYLON = {}));
  29597. var BABYLON;
  29598. (function (BABYLON) {
  29599. var PhysicsImpostor = (function () {
  29600. function PhysicsImpostor(object, type, _options, _scene) {
  29601. var _this = this;
  29602. if (_options === void 0) { _options = { mass: 0 }; }
  29603. this.object = object;
  29604. this.type = type;
  29605. this._options = _options;
  29606. this._scene = _scene;
  29607. this._bodyUpdateRequired = false;
  29608. this._onBeforePhysicsStepCallbacks = new Array();
  29609. this._onAfterPhysicsStepCallbacks = new Array();
  29610. this._onPhysicsCollideCallbacks = [];
  29611. this._deltaPosition = BABYLON.Vector3.Zero();
  29612. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  29613. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  29614. /**
  29615. * this function is executed by the physics engine.
  29616. */
  29617. this.beforeStep = function () {
  29618. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  29619. //conjugate deltaRotation
  29620. if (_this._deltaRotationConjugated) {
  29621. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  29622. }
  29623. else {
  29624. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  29625. }
  29626. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  29627. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  29628. func(_this);
  29629. });
  29630. };
  29631. /**
  29632. * this function is executed by the physics engine.
  29633. */
  29634. this.afterStep = function () {
  29635. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  29636. func(_this);
  29637. });
  29638. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  29639. _this.object.position.addInPlace(_this._deltaPosition);
  29640. if (_this._deltaRotation) {
  29641. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  29642. }
  29643. };
  29644. //event and body object due to cannon's event-based architecture.
  29645. this.onCollide = function (e) {
  29646. if (!_this._onPhysicsCollideCallbacks.length)
  29647. return;
  29648. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  29649. if (otherImpostor) {
  29650. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  29651. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  29652. }).forEach(function (obj) {
  29653. obj.callback(_this, otherImpostor);
  29654. });
  29655. }
  29656. };
  29657. //sanity check!
  29658. if (!this.object) {
  29659. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  29660. return;
  29661. }
  29662. //legacy support for old syntax.
  29663. if (!this._scene && object.getScene) {
  29664. this._scene = object.getScene();
  29665. }
  29666. this._physicsEngine = this._scene.getPhysicsEngine();
  29667. if (!this._physicsEngine) {
  29668. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  29669. }
  29670. else {
  29671. //set the object's quaternion, if not set
  29672. if (!this.object.rotationQuaternion) {
  29673. if (this.object.rotation) {
  29674. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  29675. }
  29676. else {
  29677. this.object.rotationQuaternion = new BABYLON.Quaternion();
  29678. }
  29679. }
  29680. //default options params
  29681. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  29682. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  29683. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  29684. this._joints = [];
  29685. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  29686. if (!this.object.parent) {
  29687. this._init();
  29688. }
  29689. }
  29690. }
  29691. /**
  29692. * This function will completly initialize this impostor.
  29693. * It will create a new body - but only if this mesh has no parent.
  29694. * If it has, this impostor will not be used other than to define the impostor
  29695. * of the child mesh.
  29696. */
  29697. PhysicsImpostor.prototype._init = function () {
  29698. this._physicsEngine.removeImpostor(this);
  29699. this.physicsBody = null;
  29700. this._parent = this._parent || this._getPhysicsParent();
  29701. if (!this.parent) {
  29702. this._physicsEngine.addImpostor(this);
  29703. }
  29704. };
  29705. PhysicsImpostor.prototype._getPhysicsParent = function () {
  29706. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  29707. var parentMesh = this.object.parent;
  29708. return parentMesh.physicsImpostor;
  29709. }
  29710. return;
  29711. };
  29712. /**
  29713. * Should a new body be generated.
  29714. */
  29715. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  29716. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  29717. };
  29718. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  29719. this.forceUpdate();
  29720. };
  29721. /**
  29722. * Force a regeneration of this or the parent's impostor's body.
  29723. * Use under cautious - This will remove all joints already implemented.
  29724. */
  29725. PhysicsImpostor.prototype.forceUpdate = function () {
  29726. this._init();
  29727. if (this.parent) {
  29728. this.parent.forceUpdate();
  29729. }
  29730. };
  29731. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  29732. /*public get mesh(): AbstractMesh {
  29733. return this._mesh;
  29734. }*/
  29735. /**
  29736. * Gets the body that holds this impostor. Either its own, or its parent.
  29737. */
  29738. get: function () {
  29739. return this._parent ? this._parent.physicsBody : this._physicsBody;
  29740. },
  29741. /**
  29742. * Set the physics body. Used mainly by the physics engine/plugin
  29743. */
  29744. set: function (physicsBody) {
  29745. if (this._physicsBody) {
  29746. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  29747. }
  29748. this._physicsBody = physicsBody;
  29749. this.resetUpdateFlags();
  29750. },
  29751. enumerable: true,
  29752. configurable: true
  29753. });
  29754. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  29755. get: function () {
  29756. return this._parent;
  29757. },
  29758. enumerable: true,
  29759. configurable: true
  29760. });
  29761. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  29762. this._bodyUpdateRequired = false;
  29763. };
  29764. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  29765. if (this.object.getBoundingInfo) {
  29766. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  29767. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  29768. }
  29769. else {
  29770. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  29771. }
  29772. };
  29773. PhysicsImpostor.prototype.getObjectCenter = function () {
  29774. if (this.object.getBoundingInfo) {
  29775. return this.object.getBoundingInfo().boundingBox.center;
  29776. }
  29777. else {
  29778. return this.object.position;
  29779. }
  29780. };
  29781. /**
  29782. * Get a specific parametes from the options parameter.
  29783. */
  29784. PhysicsImpostor.prototype.getParam = function (paramName) {
  29785. return this._options[paramName];
  29786. };
  29787. /**
  29788. * Sets a specific parameter in the options given to the physics plugin
  29789. */
  29790. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  29791. this._options[paramName] = value;
  29792. this._bodyUpdateRequired = true;
  29793. };
  29794. /**
  29795. * Specifically change the body's mass option. Won't recreate the physics body object
  29796. */
  29797. PhysicsImpostor.prototype.setMass = function (mass) {
  29798. if (this.getParam("mass") !== mass) {
  29799. this.setParam("mass", mass);
  29800. }
  29801. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  29802. };
  29803. PhysicsImpostor.prototype.getLinearVelocity = function () {
  29804. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  29805. };
  29806. /**
  29807. * Set the body's linear velocity.
  29808. */
  29809. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  29810. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  29811. };
  29812. PhysicsImpostor.prototype.getAngularVelocity = function () {
  29813. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  29814. };
  29815. /**
  29816. * Set the body's linear velocity.
  29817. */
  29818. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  29819. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  29820. };
  29821. /**
  29822. * Execute a function with the physics plugin native code.
  29823. * Provide a function the will have two variables - the world object and the physics body object.
  29824. */
  29825. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  29826. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  29827. };
  29828. /**
  29829. * Register a function that will be executed before the physics world is stepping forward.
  29830. */
  29831. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  29832. this._onBeforePhysicsStepCallbacks.push(func);
  29833. };
  29834. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  29835. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  29836. if (index > -1) {
  29837. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  29838. }
  29839. else {
  29840. BABYLON.Tools.Warn("Function to remove was not found");
  29841. }
  29842. };
  29843. /**
  29844. * Register a function that will be executed after the physics step
  29845. */
  29846. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  29847. this._onAfterPhysicsStepCallbacks.push(func);
  29848. };
  29849. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  29850. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  29851. if (index > -1) {
  29852. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  29853. }
  29854. else {
  29855. BABYLON.Tools.Warn("Function to remove was not found");
  29856. }
  29857. };
  29858. /**
  29859. * register a function that will be executed when this impostor collides against a different body.
  29860. */
  29861. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  29862. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29863. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  29864. };
  29865. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  29866. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  29867. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  29868. if (index > -1) {
  29869. this._onPhysicsCollideCallbacks.splice(index, 1);
  29870. }
  29871. else {
  29872. BABYLON.Tools.Warn("Function to remove was not found");
  29873. }
  29874. };
  29875. /**
  29876. * Apply a force
  29877. */
  29878. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  29879. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  29880. };
  29881. /**
  29882. * Apply an impulse
  29883. */
  29884. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  29885. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  29886. };
  29887. /**
  29888. * A help function to create a joint.
  29889. */
  29890. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  29891. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  29892. this.addJoint(otherImpostor, joint);
  29893. };
  29894. /**
  29895. * Add a joint to this impostor with a different impostor.
  29896. */
  29897. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  29898. this._joints.push({
  29899. otherImpostor: otherImpostor,
  29900. joint: joint
  29901. });
  29902. this._physicsEngine.addJoint(this, otherImpostor, joint);
  29903. };
  29904. /**
  29905. * Will keep this body still, in a sleep mode.
  29906. */
  29907. PhysicsImpostor.prototype.sleep = function () {
  29908. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  29909. };
  29910. /**
  29911. * Wake the body up.
  29912. */
  29913. PhysicsImpostor.prototype.wakeUp = function () {
  29914. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  29915. };
  29916. PhysicsImpostor.prototype.clone = function (newObject) {
  29917. if (!newObject)
  29918. return null;
  29919. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  29920. };
  29921. PhysicsImpostor.prototype.dispose = function () {
  29922. var _this = this;
  29923. //no dispose if no physics engine is available.
  29924. if (!this._physicsEngine) {
  29925. return;
  29926. }
  29927. this._joints.forEach(function (j) {
  29928. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  29929. });
  29930. //dispose the physics body
  29931. this._physicsEngine.removeImpostor(this);
  29932. if (this.parent) {
  29933. this.parent.forceUpdate();
  29934. }
  29935. else {
  29936. }
  29937. };
  29938. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  29939. this._deltaPosition.copyFrom(position);
  29940. };
  29941. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  29942. if (!this._deltaRotation) {
  29943. this._deltaRotation = new BABYLON.Quaternion();
  29944. }
  29945. this._deltaRotation.copyFrom(rotation);
  29946. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  29947. };
  29948. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  29949. //Impostor types
  29950. PhysicsImpostor.NoImpostor = 0;
  29951. PhysicsImpostor.SphereImpostor = 1;
  29952. PhysicsImpostor.BoxImpostor = 2;
  29953. PhysicsImpostor.PlaneImpostor = 3;
  29954. PhysicsImpostor.MeshImpostor = 4;
  29955. PhysicsImpostor.CylinderImpostor = 7;
  29956. PhysicsImpostor.ParticleImpostor = 8;
  29957. PhysicsImpostor.HeightmapImpostor = 9;
  29958. return PhysicsImpostor;
  29959. }());
  29960. BABYLON.PhysicsImpostor = PhysicsImpostor;
  29961. })(BABYLON || (BABYLON = {}));
  29962. var BABYLON;
  29963. (function (BABYLON) {
  29964. var PhysicsEngine = (function () {
  29965. function PhysicsEngine(gravity, _physicsPlugin) {
  29966. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  29967. this._physicsPlugin = _physicsPlugin;
  29968. //new methods and parameters
  29969. this._impostors = [];
  29970. this._joints = [];
  29971. if (!this._physicsPlugin.isSupported()) {
  29972. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  29973. + "Please make sure it is included.");
  29974. }
  29975. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  29976. this.setGravity(gravity);
  29977. this.setTimeStep();
  29978. }
  29979. PhysicsEngine.prototype.setGravity = function (gravity) {
  29980. this.gravity = gravity;
  29981. this._physicsPlugin.setGravity(this.gravity);
  29982. };
  29983. /**
  29984. * Set the time step of the physics engine.
  29985. * default is 1/60.
  29986. * To slow it down, enter 1/600 for example.
  29987. * To speed it up, 1/30
  29988. * @param {number} newTimeStep the new timestep to apply to this world.
  29989. */
  29990. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  29991. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  29992. this._physicsPlugin.setTimeStep(newTimeStep);
  29993. };
  29994. PhysicsEngine.prototype.dispose = function () {
  29995. this._impostors.forEach(function (impostor) {
  29996. impostor.dispose();
  29997. });
  29998. this._physicsPlugin.dispose();
  29999. };
  30000. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  30001. return this._physicsPlugin.name;
  30002. };
  30003. /**
  30004. * Adding a new impostor for the impostor tracking.
  30005. * This will be done by the impostor itself.
  30006. * @param {PhysicsImpostor} impostor the impostor to add
  30007. */
  30008. PhysicsEngine.prototype.addImpostor = function (impostor) {
  30009. impostor.uniqueId = this._impostors.push(impostor);
  30010. //if no parent, generate the body
  30011. if (!impostor.parent) {
  30012. this._physicsPlugin.generatePhysicsBody(impostor);
  30013. }
  30014. };
  30015. /**
  30016. * Remove an impostor from the engine.
  30017. * This impostor and its mesh will not longer be updated by the physics engine.
  30018. * @param {PhysicsImpostor} impostor the impostor to remove
  30019. */
  30020. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  30021. var index = this._impostors.indexOf(impostor);
  30022. if (index > -1) {
  30023. var removed = this._impostors.splice(index, 1);
  30024. //Is it needed?
  30025. if (removed.length) {
  30026. //this will also remove it from the world.
  30027. removed[0].physicsBody = null;
  30028. }
  30029. }
  30030. };
  30031. /**
  30032. * Add a joint to the physics engine
  30033. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  30034. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  30035. * @param {PhysicsJoint} the joint that will connect both impostors.
  30036. */
  30037. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  30038. var impostorJoint = {
  30039. mainImpostor: mainImpostor,
  30040. connectedImpostor: connectedImpostor,
  30041. joint: joint
  30042. };
  30043. joint.physicsPlugin = this._physicsPlugin;
  30044. this._joints.push(impostorJoint);
  30045. this._physicsPlugin.generateJoint(impostorJoint);
  30046. };
  30047. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  30048. var matchingJoints = this._joints.filter(function (impostorJoint) {
  30049. return (impostorJoint.connectedImpostor === connectedImpostor
  30050. && impostorJoint.joint === joint
  30051. && impostorJoint.mainImpostor === mainImpostor);
  30052. });
  30053. if (matchingJoints.length) {
  30054. this._physicsPlugin.removeJoint(matchingJoints[0]);
  30055. }
  30056. };
  30057. /**
  30058. * Called by the scene. no need to call it.
  30059. */
  30060. PhysicsEngine.prototype._step = function (delta) {
  30061. var _this = this;
  30062. //check if any mesh has no body / requires an update
  30063. this._impostors.forEach(function (impostor) {
  30064. if (impostor.isBodyInitRequired()) {
  30065. _this._physicsPlugin.generatePhysicsBody(impostor);
  30066. }
  30067. });
  30068. if (delta > 0.1) {
  30069. delta = 0.1;
  30070. }
  30071. else if (delta <= 0) {
  30072. delta = 1.0 / 60.0;
  30073. }
  30074. this._physicsPlugin.executeStep(delta, this._impostors);
  30075. };
  30076. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  30077. return this._physicsPlugin;
  30078. };
  30079. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  30080. for (var i = 0; i < this._impostors.length; ++i) {
  30081. if (this._impostors[i].object === object) {
  30082. return this._impostors[i];
  30083. }
  30084. }
  30085. };
  30086. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  30087. for (var i = 0; i < this._impostors.length; ++i) {
  30088. if (this._impostors[i].physicsBody === body) {
  30089. return this._impostors[i];
  30090. }
  30091. }
  30092. };
  30093. // Statics, Legacy support.
  30094. /**
  30095. * @Deprecated
  30096. *
  30097. */
  30098. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  30099. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  30100. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  30101. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  30102. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  30103. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  30104. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  30105. PhysicsEngine.CapsuleImpostor = -1;
  30106. PhysicsEngine.ConeImpostor = -1;
  30107. PhysicsEngine.ConvexHullImpostor = -1;
  30108. PhysicsEngine.Epsilon = 0.001;
  30109. return PhysicsEngine;
  30110. }());
  30111. BABYLON.PhysicsEngine = PhysicsEngine;
  30112. })(BABYLON || (BABYLON = {}));
  30113. var BABYLON;
  30114. (function (BABYLON) {
  30115. var VertexData = (function () {
  30116. function VertexData() {
  30117. }
  30118. VertexData.prototype.set = function (data, kind) {
  30119. switch (kind) {
  30120. case BABYLON.VertexBuffer.PositionKind:
  30121. this.positions = data;
  30122. break;
  30123. case BABYLON.VertexBuffer.NormalKind:
  30124. this.normals = data;
  30125. break;
  30126. case BABYLON.VertexBuffer.UVKind:
  30127. this.uvs = data;
  30128. break;
  30129. case BABYLON.VertexBuffer.UV2Kind:
  30130. this.uvs2 = data;
  30131. break;
  30132. case BABYLON.VertexBuffer.UV3Kind:
  30133. this.uvs3 = data;
  30134. break;
  30135. case BABYLON.VertexBuffer.UV4Kind:
  30136. this.uvs4 = data;
  30137. break;
  30138. case BABYLON.VertexBuffer.UV5Kind:
  30139. this.uvs5 = data;
  30140. break;
  30141. case BABYLON.VertexBuffer.UV6Kind:
  30142. this.uvs6 = data;
  30143. break;
  30144. case BABYLON.VertexBuffer.ColorKind:
  30145. this.colors = data;
  30146. break;
  30147. case BABYLON.VertexBuffer.MatricesIndicesKind:
  30148. this.matricesIndices = data;
  30149. break;
  30150. case BABYLON.VertexBuffer.MatricesWeightsKind:
  30151. this.matricesWeights = data;
  30152. break;
  30153. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  30154. this.matricesIndicesExtra = data;
  30155. break;
  30156. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  30157. this.matricesWeightsExtra = data;
  30158. break;
  30159. }
  30160. };
  30161. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  30162. this._applyTo(mesh, updatable);
  30163. };
  30164. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  30165. this._applyTo(geometry, updatable);
  30166. };
  30167. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  30168. this._update(mesh);
  30169. };
  30170. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  30171. this._update(geometry);
  30172. };
  30173. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  30174. if (this.positions) {
  30175. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  30176. }
  30177. if (this.normals) {
  30178. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  30179. }
  30180. if (this.uvs) {
  30181. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  30182. }
  30183. if (this.uvs2) {
  30184. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  30185. }
  30186. if (this.uvs3) {
  30187. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  30188. }
  30189. if (this.uvs4) {
  30190. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  30191. }
  30192. if (this.uvs5) {
  30193. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  30194. }
  30195. if (this.uvs6) {
  30196. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  30197. }
  30198. if (this.colors) {
  30199. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  30200. }
  30201. if (this.matricesIndices) {
  30202. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  30203. }
  30204. if (this.matricesWeights) {
  30205. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  30206. }
  30207. if (this.matricesIndicesExtra) {
  30208. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  30209. }
  30210. if (this.matricesWeightsExtra) {
  30211. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  30212. }
  30213. if (this.indices) {
  30214. meshOrGeometry.setIndices(this.indices);
  30215. }
  30216. };
  30217. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  30218. if (this.positions) {
  30219. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  30220. }
  30221. if (this.normals) {
  30222. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  30223. }
  30224. if (this.uvs) {
  30225. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  30226. }
  30227. if (this.uvs2) {
  30228. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  30229. }
  30230. if (this.uvs3) {
  30231. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  30232. }
  30233. if (this.uvs4) {
  30234. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  30235. }
  30236. if (this.uvs5) {
  30237. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  30238. }
  30239. if (this.uvs6) {
  30240. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  30241. }
  30242. if (this.colors) {
  30243. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  30244. }
  30245. if (this.matricesIndices) {
  30246. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  30247. }
  30248. if (this.matricesWeights) {
  30249. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  30250. }
  30251. if (this.matricesIndicesExtra) {
  30252. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  30253. }
  30254. if (this.matricesWeightsExtra) {
  30255. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  30256. }
  30257. if (this.indices) {
  30258. meshOrGeometry.setIndices(this.indices);
  30259. }
  30260. };
  30261. VertexData.prototype.transform = function (matrix) {
  30262. var transformed = BABYLON.Vector3.Zero();
  30263. var index;
  30264. if (this.positions) {
  30265. var position = BABYLON.Vector3.Zero();
  30266. for (index = 0; index < this.positions.length; index += 3) {
  30267. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  30268. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  30269. this.positions[index] = transformed.x;
  30270. this.positions[index + 1] = transformed.y;
  30271. this.positions[index + 2] = transformed.z;
  30272. }
  30273. }
  30274. if (this.normals) {
  30275. var normal = BABYLON.Vector3.Zero();
  30276. for (index = 0; index < this.normals.length; index += 3) {
  30277. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  30278. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  30279. this.normals[index] = transformed.x;
  30280. this.normals[index + 1] = transformed.y;
  30281. this.normals[index + 2] = transformed.z;
  30282. }
  30283. }
  30284. };
  30285. VertexData.prototype.merge = function (other) {
  30286. if (other.indices) {
  30287. if (!this.indices) {
  30288. this.indices = [];
  30289. }
  30290. var offset = this.positions ? this.positions.length / 3 : 0;
  30291. for (var index = 0; index < other.indices.length; index++) {
  30292. //TODO check type - if Int32Array!
  30293. this.indices.push(other.indices[index] + offset);
  30294. }
  30295. }
  30296. this.positions = this._mergeElement(this.positions, other.positions);
  30297. this.normals = this._mergeElement(this.normals, other.normals);
  30298. this.uvs = this._mergeElement(this.uvs, other.uvs);
  30299. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  30300. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  30301. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  30302. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  30303. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  30304. this.colors = this._mergeElement(this.colors, other.colors);
  30305. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  30306. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  30307. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  30308. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  30309. };
  30310. VertexData.prototype._mergeElement = function (source, other) {
  30311. if (!other)
  30312. return source;
  30313. if (!source)
  30314. return other;
  30315. var len = other.length + source.length;
  30316. var isSrcTypedArray = source instanceof Float32Array;
  30317. var isOthTypedArray = other instanceof Float32Array;
  30318. // use non-loop method when the source is Float32Array
  30319. if (isSrcTypedArray) {
  30320. var ret32 = new Float32Array(len);
  30321. ret32.set(source);
  30322. ret32.set(other, source.length);
  30323. return ret32;
  30324. }
  30325. else if (!isOthTypedArray) {
  30326. return source.concat(other);
  30327. }
  30328. else {
  30329. var ret = source.slice(0); // copy source to a separate array
  30330. for (var i = 0, len = other.length; i < len; i++) {
  30331. ret.push(other[i]);
  30332. }
  30333. return ret;
  30334. }
  30335. };
  30336. VertexData.prototype.serialize = function () {
  30337. var serializationObject = this.serialize();
  30338. if (this.positions) {
  30339. serializationObject.positions = this.positions;
  30340. }
  30341. if (this.normals) {
  30342. serializationObject.normals = this.normals;
  30343. }
  30344. if (this.uvs) {
  30345. serializationObject.uvs = this.uvs;
  30346. }
  30347. if (this.uvs2) {
  30348. serializationObject.uvs2 = this.uvs2;
  30349. }
  30350. if (this.uvs3) {
  30351. serializationObject.uvs3 = this.uvs3;
  30352. }
  30353. if (this.uvs4) {
  30354. serializationObject.uvs4 = this.uvs4;
  30355. }
  30356. if (this.uvs5) {
  30357. serializationObject.uvs5 = this.uvs5;
  30358. }
  30359. if (this.uvs6) {
  30360. serializationObject.uvs6 = this.uvs6;
  30361. }
  30362. if (this.colors) {
  30363. serializationObject.colors = this.colors;
  30364. }
  30365. if (this.matricesIndices) {
  30366. serializationObject.matricesIndices = this.matricesIndices;
  30367. serializationObject.matricesIndices._isExpanded = true;
  30368. }
  30369. if (this.matricesWeights) {
  30370. serializationObject.matricesWeights = this.matricesWeights;
  30371. }
  30372. if (this.matricesIndicesExtra) {
  30373. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  30374. serializationObject.matricesIndicesExtra._isExpanded = true;
  30375. }
  30376. if (this.matricesWeightsExtra) {
  30377. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  30378. }
  30379. serializationObject.indices = this.indices;
  30380. return serializationObject;
  30381. };
  30382. // Statics
  30383. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  30384. return VertexData._ExtractFrom(mesh, copyWhenShared);
  30385. };
  30386. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  30387. return VertexData._ExtractFrom(geometry, copyWhenShared);
  30388. };
  30389. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  30390. var result = new VertexData();
  30391. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30392. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  30393. }
  30394. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30395. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  30396. }
  30397. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30398. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  30399. }
  30400. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30401. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  30402. }
  30403. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  30404. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  30405. }
  30406. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  30407. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  30408. }
  30409. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  30410. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  30411. }
  30412. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  30413. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  30414. }
  30415. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  30416. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  30417. }
  30418. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30419. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  30420. }
  30421. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30422. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  30423. }
  30424. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  30425. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  30426. }
  30427. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  30428. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  30429. }
  30430. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  30431. return result;
  30432. };
  30433. VertexData.CreateRibbon = function (options) {
  30434. var pathArray = options.pathArray;
  30435. var closeArray = options.closeArray || false;
  30436. var closePath = options.closePath || false;
  30437. var invertUV = options.invertUV || false;
  30438. var defaultOffset = Math.floor(pathArray[0].length / 2);
  30439. var offset = options.offset || defaultOffset;
  30440. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  30441. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30442. var positions = [];
  30443. var indices = [];
  30444. var normals = [];
  30445. var uvs = [];
  30446. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  30447. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  30448. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  30449. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  30450. var minlg; // minimal length among all paths from pathArray
  30451. var lg = []; // array of path lengths : nb of vertex per path
  30452. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  30453. var p; // path iterator
  30454. var i; // point iterator
  30455. var j; // point iterator
  30456. // if single path in pathArray
  30457. if (pathArray.length < 2) {
  30458. var ar1 = [];
  30459. var ar2 = [];
  30460. for (i = 0; i < pathArray[0].length - offset; i++) {
  30461. ar1.push(pathArray[0][i]);
  30462. ar2.push(pathArray[0][i + offset]);
  30463. }
  30464. pathArray = [ar1, ar2];
  30465. }
  30466. // positions and horizontal distances (u)
  30467. var idc = 0;
  30468. var closePathCorr = (closePath) ? 1 : 0;
  30469. var path;
  30470. var l;
  30471. minlg = pathArray[0].length;
  30472. var vectlg;
  30473. var dist;
  30474. for (p = 0; p < pathArray.length; p++) {
  30475. uTotalDistance[p] = 0;
  30476. us[p] = [0];
  30477. path = pathArray[p];
  30478. l = path.length;
  30479. minlg = (minlg < l) ? minlg : l;
  30480. j = 0;
  30481. while (j < l) {
  30482. positions.push(path[j].x, path[j].y, path[j].z);
  30483. if (j > 0) {
  30484. vectlg = path[j].subtract(path[j - 1]).length();
  30485. dist = vectlg + uTotalDistance[p];
  30486. us[p].push(dist);
  30487. uTotalDistance[p] = dist;
  30488. }
  30489. j++;
  30490. }
  30491. if (closePath) {
  30492. j--;
  30493. positions.push(path[0].x, path[0].y, path[0].z);
  30494. vectlg = path[j].subtract(path[0]).length();
  30495. dist = vectlg + uTotalDistance[p];
  30496. us[p].push(dist);
  30497. uTotalDistance[p] = dist;
  30498. }
  30499. lg[p] = l + closePathCorr;
  30500. idx[p] = idc;
  30501. idc += (l + closePathCorr);
  30502. }
  30503. // vertical distances (v)
  30504. var path1;
  30505. var path2;
  30506. var vertex1;
  30507. var vertex2;
  30508. for (i = 0; i < minlg + closePathCorr; i++) {
  30509. vTotalDistance[i] = 0;
  30510. vs[i] = [0];
  30511. for (p = 0; p < pathArray.length - 1; p++) {
  30512. path1 = pathArray[p];
  30513. path2 = pathArray[p + 1];
  30514. if (i === minlg) {
  30515. vertex1 = path1[0];
  30516. vertex2 = path2[0];
  30517. }
  30518. else {
  30519. vertex1 = path1[i];
  30520. vertex2 = path2[i];
  30521. }
  30522. vectlg = vertex2.subtract(vertex1).length();
  30523. dist = vectlg + vTotalDistance[i];
  30524. vs[i].push(dist);
  30525. vTotalDistance[i] = dist;
  30526. }
  30527. if (closeArray) {
  30528. path1 = pathArray[p];
  30529. path2 = pathArray[0];
  30530. if (i === minlg) {
  30531. vertex2 = path2[0];
  30532. }
  30533. vectlg = vertex2.subtract(vertex1).length();
  30534. dist = vectlg + vTotalDistance[i];
  30535. vTotalDistance[i] = dist;
  30536. }
  30537. }
  30538. // uvs
  30539. var u;
  30540. var v;
  30541. for (p = 0; p < pathArray.length; p++) {
  30542. for (i = 0; i < minlg + closePathCorr; i++) {
  30543. u = us[p][i] / uTotalDistance[p];
  30544. v = vs[i][p] / vTotalDistance[i];
  30545. if (invertUV) {
  30546. uvs.push(v, u);
  30547. }
  30548. else {
  30549. uvs.push(u, v);
  30550. }
  30551. }
  30552. }
  30553. // indices
  30554. p = 0; // path index
  30555. var pi = 0; // positions array index
  30556. var l1 = lg[p] - 1; // path1 length
  30557. var l2 = lg[p + 1] - 1; // path2 length
  30558. var min = (l1 < l2) ? l1 : l2; // current path stop index
  30559. var shft = idx[1] - idx[0]; // shift
  30560. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  30561. while (pi <= min && p < path1nb) {
  30562. // 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
  30563. indices.push(pi, pi + shft, pi + 1);
  30564. indices.push(pi + shft + 1, pi + 1, pi + shft);
  30565. pi += 1;
  30566. if (pi === min) {
  30567. p++;
  30568. if (p === lg.length - 1) {
  30569. shft = idx[0] - idx[p];
  30570. l1 = lg[p] - 1;
  30571. l2 = lg[0] - 1;
  30572. }
  30573. else {
  30574. shft = idx[p + 1] - idx[p];
  30575. l1 = lg[p] - 1;
  30576. l2 = lg[p + 1] - 1;
  30577. }
  30578. pi = idx[p];
  30579. min = (l1 < l2) ? l1 + pi : l2 + pi;
  30580. }
  30581. }
  30582. // normals
  30583. VertexData.ComputeNormals(positions, indices, normals);
  30584. if (closePath) {
  30585. var indexFirst = 0;
  30586. var indexLast = 0;
  30587. for (p = 0; p < pathArray.length; p++) {
  30588. indexFirst = idx[p] * 3;
  30589. if (p + 1 < pathArray.length) {
  30590. indexLast = (idx[p + 1] - 1) * 3;
  30591. }
  30592. else {
  30593. indexLast = normals.length - 3;
  30594. }
  30595. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  30596. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  30597. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  30598. normals[indexLast] = normals[indexFirst];
  30599. normals[indexLast + 1] = normals[indexFirst + 1];
  30600. normals[indexLast + 2] = normals[indexFirst + 2];
  30601. }
  30602. }
  30603. // sides
  30604. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30605. // Result
  30606. var vertexData = new VertexData();
  30607. vertexData.indices = indices;
  30608. vertexData.positions = positions;
  30609. vertexData.normals = normals;
  30610. vertexData.uvs = uvs;
  30611. if (closePath) {
  30612. vertexData._idx = idx;
  30613. }
  30614. return vertexData;
  30615. };
  30616. VertexData.CreateBox = function (options) {
  30617. var normalsSource = [
  30618. new BABYLON.Vector3(0, 0, 1),
  30619. new BABYLON.Vector3(0, 0, -1),
  30620. new BABYLON.Vector3(1, 0, 0),
  30621. new BABYLON.Vector3(-1, 0, 0),
  30622. new BABYLON.Vector3(0, 1, 0),
  30623. new BABYLON.Vector3(0, -1, 0)
  30624. ];
  30625. var indices = [];
  30626. var positions = [];
  30627. var normals = [];
  30628. var uvs = [];
  30629. var width = options.width || options.size || 1;
  30630. var height = options.height || options.size || 1;
  30631. var depth = options.depth || options.size || 1;
  30632. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30633. var faceUV = options.faceUV || new Array(6);
  30634. var faceColors = options.faceColors;
  30635. var colors = [];
  30636. // default face colors and UV if undefined
  30637. for (var f = 0; f < 6; f++) {
  30638. if (faceUV[f] === undefined) {
  30639. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30640. }
  30641. if (faceColors && faceColors[f] === undefined) {
  30642. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30643. }
  30644. }
  30645. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  30646. // Create each face in turn.
  30647. for (var index = 0; index < normalsSource.length; index++) {
  30648. var normal = normalsSource[index];
  30649. // Get two vectors perpendicular to the face normal and to each other.
  30650. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  30651. var side2 = BABYLON.Vector3.Cross(normal, side1);
  30652. // Six indices (two triangles) per face.
  30653. var verticesLength = positions.length / 3;
  30654. indices.push(verticesLength);
  30655. indices.push(verticesLength + 1);
  30656. indices.push(verticesLength + 2);
  30657. indices.push(verticesLength);
  30658. indices.push(verticesLength + 2);
  30659. indices.push(verticesLength + 3);
  30660. // Four vertices per face.
  30661. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  30662. positions.push(vertex.x, vertex.y, vertex.z);
  30663. normals.push(normal.x, normal.y, normal.z);
  30664. uvs.push(faceUV[index].z, faceUV[index].w);
  30665. if (faceColors) {
  30666. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30667. }
  30668. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  30669. positions.push(vertex.x, vertex.y, vertex.z);
  30670. normals.push(normal.x, normal.y, normal.z);
  30671. uvs.push(faceUV[index].x, faceUV[index].w);
  30672. if (faceColors) {
  30673. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30674. }
  30675. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  30676. positions.push(vertex.x, vertex.y, vertex.z);
  30677. normals.push(normal.x, normal.y, normal.z);
  30678. uvs.push(faceUV[index].x, faceUV[index].y);
  30679. if (faceColors) {
  30680. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30681. }
  30682. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  30683. positions.push(vertex.x, vertex.y, vertex.z);
  30684. normals.push(normal.x, normal.y, normal.z);
  30685. uvs.push(faceUV[index].z, faceUV[index].y);
  30686. if (faceColors) {
  30687. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  30688. }
  30689. }
  30690. // sides
  30691. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30692. // Result
  30693. var vertexData = new VertexData();
  30694. vertexData.indices = indices;
  30695. vertexData.positions = positions;
  30696. vertexData.normals = normals;
  30697. vertexData.uvs = uvs;
  30698. if (faceColors) {
  30699. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  30700. vertexData.colors = totalColors;
  30701. }
  30702. return vertexData;
  30703. };
  30704. VertexData.CreateSphere = function (options) {
  30705. var segments = options.segments || 32;
  30706. var diameterX = options.diameterX || options.diameter || 1;
  30707. var diameterY = options.diameterY || options.diameter || 1;
  30708. var diameterZ = options.diameterZ || options.diameter || 1;
  30709. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30710. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  30711. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30712. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  30713. var totalZRotationSteps = 2 + segments;
  30714. var totalYRotationSteps = 2 * totalZRotationSteps;
  30715. var indices = [];
  30716. var positions = [];
  30717. var normals = [];
  30718. var uvs = [];
  30719. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  30720. var normalizedZ = zRotationStep / totalZRotationSteps;
  30721. var angleZ = normalizedZ * Math.PI * slice;
  30722. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  30723. var normalizedY = yRotationStep / totalYRotationSteps;
  30724. var angleY = normalizedY * Math.PI * 2 * arc;
  30725. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  30726. var rotationY = BABYLON.Matrix.RotationY(angleY);
  30727. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  30728. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  30729. var vertex = complete.multiply(radius);
  30730. var normal = complete.divide(radius).normalize();
  30731. positions.push(vertex.x, vertex.y, vertex.z);
  30732. normals.push(normal.x, normal.y, normal.z);
  30733. uvs.push(normalizedY, normalizedZ);
  30734. }
  30735. if (zRotationStep > 0) {
  30736. var verticesCount = positions.length / 3;
  30737. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  30738. indices.push((firstIndex));
  30739. indices.push((firstIndex + 1));
  30740. indices.push(firstIndex + totalYRotationSteps + 1);
  30741. indices.push((firstIndex + totalYRotationSteps + 1));
  30742. indices.push((firstIndex + 1));
  30743. indices.push((firstIndex + totalYRotationSteps + 2));
  30744. }
  30745. }
  30746. }
  30747. // Sides
  30748. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30749. // Result
  30750. var vertexData = new VertexData();
  30751. vertexData.indices = indices;
  30752. vertexData.positions = positions;
  30753. vertexData.normals = normals;
  30754. vertexData.uvs = uvs;
  30755. return vertexData;
  30756. };
  30757. // Cylinder and cone
  30758. VertexData.CreateCylinder = function (options) {
  30759. var height = options.height || 2;
  30760. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  30761. var diameterBottom = options.diameterBottom || options.diameter || 1;
  30762. var tessellation = options.tessellation || 24;
  30763. var subdivisions = options.subdivisions || 1;
  30764. var hasRings = options.hasRings;
  30765. var enclose = options.enclose;
  30766. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  30767. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30768. var faceUV = options.faceUV || new Array(3);
  30769. var faceColors = options.faceColors;
  30770. // default face colors and UV if undefined
  30771. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  30772. var ringNb = (hasRings) ? subdivisions : 1;
  30773. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  30774. var f;
  30775. for (f = 0; f < surfaceNb; f++) {
  30776. if (faceColors && faceColors[f] === undefined) {
  30777. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  30778. }
  30779. }
  30780. for (f = 0; f < surfaceNb; f++) {
  30781. if (faceUV && faceUV[f] === undefined) {
  30782. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  30783. }
  30784. }
  30785. var indices = [];
  30786. var positions = [];
  30787. var normals = [];
  30788. var uvs = [];
  30789. var colors = [];
  30790. var angle_step = Math.PI * 2 * arc / tessellation;
  30791. var angle;
  30792. var h;
  30793. var radius;
  30794. var tan = (diameterBottom - diameterTop) / 2 / height;
  30795. var ringVertex = BABYLON.Vector3.Zero();
  30796. var ringNormal = BABYLON.Vector3.Zero();
  30797. var ringFirstVertex = BABYLON.Vector3.Zero();
  30798. var ringFirstNormal = BABYLON.Vector3.Zero();
  30799. var quadNormal = BABYLON.Vector3.Zero();
  30800. var Y = BABYLON.Axis.Y;
  30801. // positions, normals, uvs
  30802. var i;
  30803. var j;
  30804. var r;
  30805. var ringIdx = 1;
  30806. var s = 1; // surface index
  30807. var cs = 0;
  30808. var v = 0;
  30809. for (i = 0; i <= subdivisions; i++) {
  30810. h = i / subdivisions;
  30811. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  30812. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  30813. for (r = 0; r < ringIdx; r++) {
  30814. if (hasRings) {
  30815. s += r;
  30816. }
  30817. if (enclose) {
  30818. s += 2 * r;
  30819. }
  30820. for (j = 0; j <= tessellation; j++) {
  30821. angle = j * angle_step;
  30822. // position
  30823. ringVertex.x = Math.cos(-angle) * radius;
  30824. ringVertex.y = -height / 2 + h * height;
  30825. ringVertex.z = Math.sin(-angle) * radius;
  30826. // normal
  30827. if (diameterTop === 0 && i === subdivisions) {
  30828. // if no top cap, reuse former normals
  30829. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  30830. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  30831. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  30832. }
  30833. else {
  30834. ringNormal.x = ringVertex.x;
  30835. ringNormal.z = ringVertex.z;
  30836. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  30837. ringNormal.normalize();
  30838. }
  30839. // keep first ring vertex values for enclose
  30840. if (j === 0) {
  30841. ringFirstVertex.copyFrom(ringVertex);
  30842. ringFirstNormal.copyFrom(ringNormal);
  30843. }
  30844. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30845. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  30846. if (hasRings) {
  30847. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  30848. }
  30849. else {
  30850. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  30851. }
  30852. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  30853. if (faceColors) {
  30854. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  30855. }
  30856. }
  30857. // if enclose, add four vertices and their dedicated normals
  30858. if (arc !== 1 && enclose) {
  30859. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  30860. positions.push(0, ringVertex.y, 0);
  30861. positions.push(0, ringVertex.y, 0);
  30862. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  30863. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  30864. quadNormal.normalize();
  30865. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30866. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  30867. quadNormal.normalize();
  30868. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  30869. if (hasRings) {
  30870. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  30871. }
  30872. else {
  30873. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  30874. }
  30875. uvs.push(faceUV[s + 1].x, v);
  30876. uvs.push(faceUV[s + 1].z, v);
  30877. if (hasRings) {
  30878. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  30879. }
  30880. else {
  30881. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  30882. }
  30883. uvs.push(faceUV[s + 2].x, v);
  30884. uvs.push(faceUV[s + 2].z, v);
  30885. if (faceColors) {
  30886. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30887. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  30888. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30889. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  30890. }
  30891. }
  30892. if (cs !== s) {
  30893. cs = s;
  30894. }
  30895. }
  30896. }
  30897. // indices
  30898. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  30899. var s;
  30900. i = 0;
  30901. for (s = 0; s < subdivisions; s++) {
  30902. for (j = 0; j < tessellation; j++) {
  30903. var i0 = i * (e + 1) + j;
  30904. var i1 = (i + 1) * (e + 1) + j;
  30905. var i2 = i * (e + 1) + (j + 1);
  30906. var i3 = (i + 1) * (e + 1) + (j + 1);
  30907. indices.push(i0, i1, i2);
  30908. indices.push(i3, i2, i1);
  30909. }
  30910. if (arc !== 1 && enclose) {
  30911. indices.push(i0 + 2, i1 + 2, i2 + 2);
  30912. indices.push(i3 + 2, i2 + 2, i1 + 2);
  30913. indices.push(i0 + 4, i1 + 4, i2 + 4);
  30914. indices.push(i3 + 4, i2 + 4, i1 + 4);
  30915. }
  30916. i = (hasRings) ? (i + 2) : (i + 1);
  30917. }
  30918. // Caps
  30919. var createCylinderCap = function (isTop) {
  30920. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  30921. if (radius === 0) {
  30922. return;
  30923. }
  30924. // Cap positions, normals & uvs
  30925. var angle;
  30926. var circleVector;
  30927. var i;
  30928. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  30929. var c;
  30930. if (faceColors) {
  30931. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  30932. }
  30933. // cap center
  30934. var vbase = positions.length / 3;
  30935. var offset = isTop ? height / 2 : -height / 2;
  30936. var center = new BABYLON.Vector3(0, offset, 0);
  30937. positions.push(center.x, center.y, center.z);
  30938. normals.push(0, isTop ? 1 : -1, 0);
  30939. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  30940. if (faceColors) {
  30941. colors.push(c.r, c.g, c.b, c.a);
  30942. }
  30943. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  30944. for (i = 0; i <= tessellation; i++) {
  30945. angle = Math.PI * 2 * i * arc / tessellation;
  30946. var cos = Math.cos(-angle);
  30947. var sin = Math.sin(-angle);
  30948. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  30949. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  30950. positions.push(circleVector.x, circleVector.y, circleVector.z);
  30951. normals.push(0, isTop ? 1 : -1, 0);
  30952. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  30953. if (faceColors) {
  30954. colors.push(c.r, c.g, c.b, c.a);
  30955. }
  30956. }
  30957. // Cap indices
  30958. for (i = 0; i < tessellation; i++) {
  30959. if (!isTop) {
  30960. indices.push(vbase);
  30961. indices.push(vbase + (i + 1));
  30962. indices.push(vbase + (i + 2));
  30963. }
  30964. else {
  30965. indices.push(vbase);
  30966. indices.push(vbase + (i + 2));
  30967. indices.push(vbase + (i + 1));
  30968. }
  30969. }
  30970. };
  30971. // add caps to geometry
  30972. createCylinderCap(false);
  30973. createCylinderCap(true);
  30974. // Sides
  30975. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  30976. var vertexData = new VertexData();
  30977. vertexData.indices = indices;
  30978. vertexData.positions = positions;
  30979. vertexData.normals = normals;
  30980. vertexData.uvs = uvs;
  30981. if (faceColors) {
  30982. vertexData.colors = colors;
  30983. }
  30984. return vertexData;
  30985. };
  30986. VertexData.CreateTorus = function (options) {
  30987. var indices = [];
  30988. var positions = [];
  30989. var normals = [];
  30990. var uvs = [];
  30991. var diameter = options.diameter || 1;
  30992. var thickness = options.thickness || 0.5;
  30993. var tessellation = options.tessellation || 16;
  30994. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  30995. var stride = tessellation + 1;
  30996. for (var i = 0; i <= tessellation; i++) {
  30997. var u = i / tessellation;
  30998. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  30999. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  31000. for (var j = 0; j <= tessellation; j++) {
  31001. var v = 1 - j / tessellation;
  31002. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  31003. var dx = Math.cos(innerAngle);
  31004. var dy = Math.sin(innerAngle);
  31005. // Create a vertex.
  31006. var normal = new BABYLON.Vector3(dx, dy, 0);
  31007. var position = normal.scale(thickness / 2);
  31008. var textureCoordinate = new BABYLON.Vector2(u, v);
  31009. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  31010. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  31011. positions.push(position.x, position.y, position.z);
  31012. normals.push(normal.x, normal.y, normal.z);
  31013. uvs.push(textureCoordinate.x, textureCoordinate.y);
  31014. // And create indices for two triangles.
  31015. var nextI = (i + 1) % stride;
  31016. var nextJ = (j + 1) % stride;
  31017. indices.push(i * stride + j);
  31018. indices.push(i * stride + nextJ);
  31019. indices.push(nextI * stride + j);
  31020. indices.push(i * stride + nextJ);
  31021. indices.push(nextI * stride + nextJ);
  31022. indices.push(nextI * stride + j);
  31023. }
  31024. }
  31025. // Sides
  31026. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31027. // Result
  31028. var vertexData = new VertexData();
  31029. vertexData.indices = indices;
  31030. vertexData.positions = positions;
  31031. vertexData.normals = normals;
  31032. vertexData.uvs = uvs;
  31033. return vertexData;
  31034. };
  31035. VertexData.CreateLineSystem = function (options) {
  31036. var indices = [];
  31037. var positions = [];
  31038. var lines = options.lines;
  31039. var idx = 0;
  31040. for (var l = 0; l < lines.length; l++) {
  31041. var points = lines[l];
  31042. for (var index = 0; index < points.length; index++) {
  31043. positions.push(points[index].x, points[index].y, points[index].z);
  31044. if (index > 0) {
  31045. indices.push(idx - 1);
  31046. indices.push(idx);
  31047. }
  31048. idx++;
  31049. }
  31050. }
  31051. var vertexData = new VertexData();
  31052. vertexData.indices = indices;
  31053. vertexData.positions = positions;
  31054. return vertexData;
  31055. };
  31056. VertexData.CreateDashedLines = function (options) {
  31057. var dashSize = options.dashSize || 3;
  31058. var gapSize = options.gapSize || 1;
  31059. var dashNb = options.dashNb || 200;
  31060. var points = options.points;
  31061. var positions = new Array();
  31062. var indices = new Array();
  31063. var curvect = BABYLON.Vector3.Zero();
  31064. var lg = 0;
  31065. var nb = 0;
  31066. var shft = 0;
  31067. var dashshft = 0;
  31068. var curshft = 0;
  31069. var idx = 0;
  31070. var i = 0;
  31071. for (i = 0; i < points.length - 1; i++) {
  31072. points[i + 1].subtractToRef(points[i], curvect);
  31073. lg += curvect.length();
  31074. }
  31075. shft = lg / dashNb;
  31076. dashshft = dashSize * shft / (dashSize + gapSize);
  31077. for (i = 0; i < points.length - 1; i++) {
  31078. points[i + 1].subtractToRef(points[i], curvect);
  31079. nb = Math.floor(curvect.length() / shft);
  31080. curvect.normalize();
  31081. for (var j = 0; j < nb; j++) {
  31082. curshft = shft * j;
  31083. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  31084. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  31085. indices.push(idx, idx + 1);
  31086. idx += 2;
  31087. }
  31088. }
  31089. // Result
  31090. var vertexData = new VertexData();
  31091. vertexData.positions = positions;
  31092. vertexData.indices = indices;
  31093. return vertexData;
  31094. };
  31095. VertexData.CreateGround = function (options) {
  31096. var indices = [];
  31097. var positions = [];
  31098. var normals = [];
  31099. var uvs = [];
  31100. var row, col;
  31101. var width = options.width || 1;
  31102. var height = options.height || 1;
  31103. var subdivisions = options.subdivisions || 1;
  31104. for (row = 0; row <= subdivisions; row++) {
  31105. for (col = 0; col <= subdivisions; col++) {
  31106. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  31107. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31108. positions.push(position.x, position.y, position.z);
  31109. normals.push(normal.x, normal.y, normal.z);
  31110. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  31111. }
  31112. }
  31113. for (row = 0; row < subdivisions; row++) {
  31114. for (col = 0; col < subdivisions; col++) {
  31115. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  31116. indices.push(col + 1 + row * (subdivisions + 1));
  31117. indices.push(col + row * (subdivisions + 1));
  31118. indices.push(col + (row + 1) * (subdivisions + 1));
  31119. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  31120. indices.push(col + row * (subdivisions + 1));
  31121. }
  31122. }
  31123. // Result
  31124. var vertexData = new VertexData();
  31125. vertexData.indices = indices;
  31126. vertexData.positions = positions;
  31127. vertexData.normals = normals;
  31128. vertexData.uvs = uvs;
  31129. return vertexData;
  31130. };
  31131. VertexData.CreateTiledGround = function (options) {
  31132. var xmin = options.xmin || -1.0;
  31133. var zmin = options.zmin || -1.0;
  31134. var xmax = options.xmax || 1.0;
  31135. var zmax = options.zmax || 1.0;
  31136. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  31137. var precision = options.precision || { w: 1, h: 1 };
  31138. var indices = [];
  31139. var positions = [];
  31140. var normals = [];
  31141. var uvs = [];
  31142. var row, col, tileRow, tileCol;
  31143. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  31144. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  31145. precision.w = (precision.w < 1) ? 1 : precision.w;
  31146. precision.h = (precision.h < 1) ? 1 : precision.h;
  31147. var tileSize = {
  31148. 'w': (xmax - xmin) / subdivisions.w,
  31149. 'h': (zmax - zmin) / subdivisions.h
  31150. };
  31151. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  31152. // Indices
  31153. var base = positions.length / 3;
  31154. var rowLength = precision.w + 1;
  31155. for (row = 0; row < precision.h; row++) {
  31156. for (col = 0; col < precision.w; col++) {
  31157. var square = [
  31158. base + col + row * rowLength,
  31159. base + (col + 1) + row * rowLength,
  31160. base + (col + 1) + (row + 1) * rowLength,
  31161. base + col + (row + 1) * rowLength
  31162. ];
  31163. indices.push(square[1]);
  31164. indices.push(square[2]);
  31165. indices.push(square[3]);
  31166. indices.push(square[0]);
  31167. indices.push(square[1]);
  31168. indices.push(square[3]);
  31169. }
  31170. }
  31171. // Position, normals and uvs
  31172. var position = BABYLON.Vector3.Zero();
  31173. var normal = new BABYLON.Vector3(0, 1.0, 0);
  31174. for (row = 0; row <= precision.h; row++) {
  31175. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  31176. for (col = 0; col <= precision.w; col++) {
  31177. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  31178. position.y = 0;
  31179. positions.push(position.x, position.y, position.z);
  31180. normals.push(normal.x, normal.y, normal.z);
  31181. uvs.push(col / precision.w, row / precision.h);
  31182. }
  31183. }
  31184. }
  31185. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  31186. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  31187. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  31188. }
  31189. }
  31190. // Result
  31191. var vertexData = new VertexData();
  31192. vertexData.indices = indices;
  31193. vertexData.positions = positions;
  31194. vertexData.normals = normals;
  31195. vertexData.uvs = uvs;
  31196. return vertexData;
  31197. };
  31198. VertexData.CreateGroundFromHeightMap = function (options) {
  31199. var indices = [];
  31200. var positions = [];
  31201. var normals = [];
  31202. var uvs = [];
  31203. var row, col;
  31204. // Vertices
  31205. for (row = 0; row <= options.subdivisions; row++) {
  31206. for (col = 0; col <= options.subdivisions; col++) {
  31207. 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));
  31208. // Compute height
  31209. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  31210. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  31211. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  31212. var r = options.buffer[pos] / 255.0;
  31213. var g = options.buffer[pos + 1] / 255.0;
  31214. var b = options.buffer[pos + 2] / 255.0;
  31215. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  31216. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  31217. // Add vertex
  31218. positions.push(position.x, position.y, position.z);
  31219. normals.push(0, 0, 0);
  31220. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  31221. }
  31222. }
  31223. // Indices
  31224. for (row = 0; row < options.subdivisions; row++) {
  31225. for (col = 0; col < options.subdivisions; col++) {
  31226. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31227. indices.push(col + 1 + row * (options.subdivisions + 1));
  31228. indices.push(col + row * (options.subdivisions + 1));
  31229. indices.push(col + (row + 1) * (options.subdivisions + 1));
  31230. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  31231. indices.push(col + row * (options.subdivisions + 1));
  31232. }
  31233. }
  31234. // Normals
  31235. VertexData.ComputeNormals(positions, indices, normals);
  31236. // Result
  31237. var vertexData = new VertexData();
  31238. vertexData.indices = indices;
  31239. vertexData.positions = positions;
  31240. vertexData.normals = normals;
  31241. vertexData.uvs = uvs;
  31242. return vertexData;
  31243. };
  31244. VertexData.CreatePlane = function (options) {
  31245. var indices = [];
  31246. var positions = [];
  31247. var normals = [];
  31248. var uvs = [];
  31249. var width = options.width || options.size || 1;
  31250. var height = options.height || options.size || 1;
  31251. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31252. // Vertices
  31253. var halfWidth = width / 2.0;
  31254. var halfHeight = height / 2.0;
  31255. positions.push(-halfWidth, -halfHeight, 0);
  31256. normals.push(0, 0, -1.0);
  31257. uvs.push(0.0, 0.0);
  31258. positions.push(halfWidth, -halfHeight, 0);
  31259. normals.push(0, 0, -1.0);
  31260. uvs.push(1.0, 0.0);
  31261. positions.push(halfWidth, halfHeight, 0);
  31262. normals.push(0, 0, -1.0);
  31263. uvs.push(1.0, 1.0);
  31264. positions.push(-halfWidth, halfHeight, 0);
  31265. normals.push(0, 0, -1.0);
  31266. uvs.push(0.0, 1.0);
  31267. // Indices
  31268. indices.push(0);
  31269. indices.push(1);
  31270. indices.push(2);
  31271. indices.push(0);
  31272. indices.push(2);
  31273. indices.push(3);
  31274. // Sides
  31275. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31276. // Result
  31277. var vertexData = new VertexData();
  31278. vertexData.indices = indices;
  31279. vertexData.positions = positions;
  31280. vertexData.normals = normals;
  31281. vertexData.uvs = uvs;
  31282. return vertexData;
  31283. };
  31284. VertexData.CreateDisc = function (options) {
  31285. var positions = [];
  31286. var indices = [];
  31287. var normals = [];
  31288. var uvs = [];
  31289. var radius = options.radius || 0.5;
  31290. var tessellation = options.tessellation || 64;
  31291. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31292. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31293. // positions and uvs
  31294. positions.push(0, 0, 0); // disc center first
  31295. uvs.push(0.5, 0.5);
  31296. var theta = Math.PI * 2 * arc;
  31297. var step = theta / tessellation;
  31298. for (var a = 0; a < theta; a += step) {
  31299. var x = Math.cos(a);
  31300. var y = Math.sin(a);
  31301. var u = (x + 1) / 2;
  31302. var v = (1 - y) / 2;
  31303. positions.push(radius * x, radius * y, 0);
  31304. uvs.push(u, v);
  31305. }
  31306. if (arc === 1) {
  31307. positions.push(positions[3], positions[4], positions[5]); // close the circle
  31308. uvs.push(uvs[2], uvs[3]);
  31309. }
  31310. //indices
  31311. var vertexNb = positions.length / 3;
  31312. for (var i = 1; i < vertexNb - 1; i++) {
  31313. indices.push(i + 1, 0, i);
  31314. }
  31315. // result
  31316. VertexData.ComputeNormals(positions, indices, normals);
  31317. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31318. var vertexData = new VertexData();
  31319. vertexData.indices = indices;
  31320. vertexData.positions = positions;
  31321. vertexData.normals = normals;
  31322. vertexData.uvs = uvs;
  31323. return vertexData;
  31324. };
  31325. VertexData.CreateIcoSphere = function (options) {
  31326. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31327. var radius = options.radius || 1;
  31328. var flat = (options.flat === undefined) ? true : options.flat;
  31329. var subdivisions = options.subdivisions || 4;
  31330. var radiusX = options.radiusX || radius;
  31331. var radiusY = options.radiusY || radius;
  31332. var radiusZ = options.radiusZ || radius;
  31333. var t = (1 + Math.sqrt(5)) / 2;
  31334. // 12 vertex x,y,z
  31335. var ico_vertices = [
  31336. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  31337. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  31338. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  31339. ];
  31340. // index of 3 vertex makes a face of icopshere
  31341. var ico_indices = [
  31342. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  31343. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  31344. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  31345. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  31346. ];
  31347. // vertex for uv have aliased position, not for UV
  31348. var vertices_unalias_id = [
  31349. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  31350. // vertex alias
  31351. 0,
  31352. 2,
  31353. 3,
  31354. 3,
  31355. 3,
  31356. 4,
  31357. 7,
  31358. 8,
  31359. 9,
  31360. 9,
  31361. 10,
  31362. 11 // 23: B + 12
  31363. ];
  31364. // uv as integer step (not pixels !)
  31365. var ico_vertexuv = [
  31366. 5, 1, 3, 1, 6, 4, 0, 0,
  31367. 5, 3, 4, 2, 2, 2, 4, 0,
  31368. 2, 0, 1, 1, 6, 0, 6, 2,
  31369. // vertex alias (for same vertex on different faces)
  31370. 0, 4,
  31371. 3, 3,
  31372. 4, 4,
  31373. 3, 1,
  31374. 4, 2,
  31375. 4, 4,
  31376. 0, 2,
  31377. 1, 1,
  31378. 2, 2,
  31379. 3, 3,
  31380. 1, 3,
  31381. 2, 4 // 23: B + 12
  31382. ];
  31383. // Vertices[0, 1, ...9, A, B] : position on UV plane
  31384. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  31385. // First island of uv mapping
  31386. // v = 4h 3+ 2
  31387. // v = 3h 9+ 4
  31388. // v = 2h 9+ 5 B
  31389. // v = 1h 9 1 0
  31390. // v = 0h 3 8 7 A
  31391. // u = 0 1 2 3 4 5 6 *a
  31392. // Second island of uv mapping
  31393. // v = 4h 0+ B+ 4+
  31394. // v = 3h A+ 2+
  31395. // v = 2h 7+ 6 3+
  31396. // v = 1h 8+ 3+
  31397. // v = 0h
  31398. // u = 0 1 2 3 4 5 6 *a
  31399. // Face layout on texture UV mapping
  31400. // ============
  31401. // \ 4 /\ 16 / ======
  31402. // \ / \ / /\ 11 /
  31403. // \/ 7 \/ / \ /
  31404. // ======= / 10 \/
  31405. // /\ 17 /\ =======
  31406. // / \ / \ \ 15 /\
  31407. // / 8 \/ 12 \ \ / \
  31408. // ============ \/ 6 \
  31409. // \ 18 /\ ============
  31410. // \ / \ \ 5 /\ 0 /
  31411. // \/ 13 \ \ / \ /
  31412. // ======= \/ 1 \/
  31413. // =============
  31414. // /\ 19 /\ 2 /\
  31415. // / \ / \ / \
  31416. // / 14 \/ 9 \/ 3 \
  31417. // ===================
  31418. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  31419. var ustep = 138 / 1024;
  31420. var vstep = 239 / 1024;
  31421. var uoffset = 60 / 1024;
  31422. var voffset = 26 / 1024;
  31423. // Second island should have margin, not to touch the first island
  31424. // avoid any borderline artefact in pixel rounding
  31425. var island_u_offset = -40 / 1024;
  31426. var island_v_offset = +20 / 1024;
  31427. // face is either island 0 or 1 :
  31428. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  31429. var island = [
  31430. 0, 0, 0, 0, 1,
  31431. 0, 0, 1, 1, 0,
  31432. 0, 0, 1, 1, 0,
  31433. 0, 1, 1, 1, 0 // 15 - 19
  31434. ];
  31435. var indices = [];
  31436. var positions = [];
  31437. var normals = [];
  31438. var uvs = [];
  31439. var current_indice = 0;
  31440. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  31441. var face_vertex_pos = new Array(3);
  31442. var face_vertex_uv = new Array(3);
  31443. var v012;
  31444. for (v012 = 0; v012 < 3; v012++) {
  31445. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  31446. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  31447. }
  31448. // create all with normals
  31449. for (var face = 0; face < 20; face++) {
  31450. // 3 vertex per face
  31451. for (v012 = 0; v012 < 3; v012++) {
  31452. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  31453. var v_id = ico_indices[3 * face + v012];
  31454. // vertex have 3D position (x,y,z)
  31455. 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]);
  31456. // Normalize to get normal, then scale to radius
  31457. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  31458. // uv Coordinates from vertex ID
  31459. 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);
  31460. }
  31461. // Subdivide the face (interpolate pos, norm, uv)
  31462. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  31463. // - norm is linear interpolation of vertex corner normal
  31464. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  31465. // - uv is linear interpolation
  31466. //
  31467. // Topology is as below for sub-divide by 2
  31468. // vertex shown as v0,v1,v2
  31469. // interp index is i1 to progress in range [v0,v1[
  31470. // interp index is i2 to progress in range [v0,v2[
  31471. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  31472. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31473. //
  31474. //
  31475. // i2 v2
  31476. // ^ ^
  31477. // / / \
  31478. // / / \
  31479. // / / \
  31480. // / / (0,1) \
  31481. // / #---------\
  31482. // / / \ (0,0)'/ \
  31483. // / / \ / \
  31484. // / / \ / \
  31485. // / / (0,0) \ / (1,0) \
  31486. // / #---------#---------\
  31487. // v0 v1
  31488. //
  31489. // --------------------> i1
  31490. //
  31491. // interp of (i1,i2):
  31492. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  31493. // along i1 : lerp(x0,x1, i1/(S-i2))
  31494. //
  31495. // centroid of triangle is needed to get help normal computation
  31496. // (c1,c2) are used for centroid location
  31497. var interp_vertex = function (i1, i2, c1, c2) {
  31498. // vertex is interpolated from
  31499. // - face_vertex_pos[0..2]
  31500. // - face_vertex_uv[0..2]
  31501. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  31502. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  31503. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  31504. pos_interp.normalize();
  31505. var vertex_normal;
  31506. if (flat) {
  31507. // in flat mode, recalculate normal as face centroid normal
  31508. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  31509. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  31510. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  31511. }
  31512. else {
  31513. // in smooth mode, recalculate normal from each single vertex position
  31514. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  31515. }
  31516. // Vertex normal need correction due to X,Y,Z radius scaling
  31517. vertex_normal.x /= radiusX;
  31518. vertex_normal.y /= radiusY;
  31519. vertex_normal.z /= radiusZ;
  31520. vertex_normal.normalize();
  31521. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  31522. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  31523. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  31524. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  31525. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  31526. uvs.push(uv_interp.x, uv_interp.y);
  31527. // push each vertex has member of a face
  31528. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  31529. indices.push(current_indice);
  31530. current_indice++;
  31531. };
  31532. for (var i2 = 0; i2 < subdivisions; i2++) {
  31533. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  31534. // face : (i1,i2) for /\ :
  31535. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  31536. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31537. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31538. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  31539. if (i1 + i2 + 1 < subdivisions) {
  31540. // face : (i1,i2)' for \/ :
  31541. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  31542. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31543. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31544. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  31545. }
  31546. }
  31547. }
  31548. }
  31549. // Sides
  31550. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31551. // Result
  31552. var vertexData = new VertexData();
  31553. vertexData.indices = indices;
  31554. vertexData.positions = positions;
  31555. vertexData.normals = normals;
  31556. vertexData.uvs = uvs;
  31557. return vertexData;
  31558. };
  31559. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  31560. VertexData.CreatePolyhedron = function (options) {
  31561. // provided polyhedron types :
  31562. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  31563. // 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)
  31564. var polyhedra = [];
  31565. 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]] };
  31566. 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]] };
  31567. polyhedra[2] = {
  31568. 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]],
  31569. 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]]
  31570. };
  31571. polyhedra[3] = {
  31572. 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]],
  31573. 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]]
  31574. };
  31575. polyhedra[4] = {
  31576. 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]],
  31577. 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]]
  31578. };
  31579. 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]] };
  31580. 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]] };
  31581. 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]] };
  31582. 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]] };
  31583. 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]] };
  31584. 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]] };
  31585. 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]] };
  31586. 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]] };
  31587. 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]] };
  31588. polyhedra[14] = {
  31589. 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]],
  31590. 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]]
  31591. };
  31592. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  31593. var size = options.size;
  31594. var sizeX = options.sizeX || size || 1;
  31595. var sizeY = options.sizeY || size || 1;
  31596. var sizeZ = options.sizeZ || size || 1;
  31597. var data = options.custom || polyhedra[type];
  31598. var nbfaces = data.face.length;
  31599. var faceUV = options.faceUV || new Array(nbfaces);
  31600. var faceColors = options.faceColors;
  31601. var flat = (options.flat === undefined) ? true : options.flat;
  31602. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31603. var positions = [];
  31604. var indices = [];
  31605. var normals = [];
  31606. var uvs = [];
  31607. var colors = [];
  31608. var index = 0;
  31609. var faceIdx = 0; // face cursor in the array "indexes"
  31610. var indexes = [];
  31611. var i = 0;
  31612. var f = 0;
  31613. var u, v, ang, x, y, tmp;
  31614. // default face colors and UV if undefined
  31615. if (flat) {
  31616. for (f = 0; f < nbfaces; f++) {
  31617. if (faceColors && faceColors[f] === undefined) {
  31618. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31619. }
  31620. if (faceUV && faceUV[f] === undefined) {
  31621. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31622. }
  31623. }
  31624. }
  31625. if (!flat) {
  31626. for (i = 0; i < data.vertex.length; i++) {
  31627. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  31628. uvs.push(0, 0);
  31629. }
  31630. for (f = 0; f < nbfaces; f++) {
  31631. for (i = 0; i < data.face[f].length - 2; i++) {
  31632. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  31633. }
  31634. }
  31635. }
  31636. else {
  31637. for (f = 0; f < nbfaces; f++) {
  31638. var fl = data.face[f].length; // number of vertices of the current face
  31639. ang = 2 * Math.PI / fl;
  31640. x = 0.5 * Math.tan(ang / 2);
  31641. y = 0.5;
  31642. // positions, uvs, colors
  31643. for (i = 0; i < fl; i++) {
  31644. // positions
  31645. 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);
  31646. indexes.push(index);
  31647. index++;
  31648. // uvs
  31649. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  31650. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  31651. uvs.push(u, v);
  31652. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  31653. y = x * Math.sin(ang) + y * Math.cos(ang);
  31654. x = tmp;
  31655. // colors
  31656. if (faceColors) {
  31657. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  31658. }
  31659. }
  31660. // indices from indexes
  31661. for (i = 0; i < fl - 2; i++) {
  31662. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  31663. }
  31664. faceIdx += fl;
  31665. }
  31666. }
  31667. VertexData.ComputeNormals(positions, indices, normals);
  31668. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31669. var vertexData = new VertexData();
  31670. vertexData.positions = positions;
  31671. vertexData.indices = indices;
  31672. vertexData.normals = normals;
  31673. vertexData.uvs = uvs;
  31674. if (faceColors && flat) {
  31675. vertexData.colors = colors;
  31676. }
  31677. return vertexData;
  31678. };
  31679. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  31680. VertexData.CreateTorusKnot = function (options) {
  31681. var indices = [];
  31682. var positions = [];
  31683. var normals = [];
  31684. var uvs = [];
  31685. var radius = options.radius || 2;
  31686. var tube = options.tube || 0.5;
  31687. var radialSegments = options.radialSegments || 32;
  31688. var tubularSegments = options.tubularSegments || 32;
  31689. var p = options.p || 2;
  31690. var q = options.q || 3;
  31691. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31692. // Helper
  31693. var getPos = function (angle) {
  31694. var cu = Math.cos(angle);
  31695. var su = Math.sin(angle);
  31696. var quOverP = q / p * angle;
  31697. var cs = Math.cos(quOverP);
  31698. var tx = radius * (2 + cs) * 0.5 * cu;
  31699. var ty = radius * (2 + cs) * su * 0.5;
  31700. var tz = radius * Math.sin(quOverP) * 0.5;
  31701. return new BABYLON.Vector3(tx, ty, tz);
  31702. };
  31703. // Vertices
  31704. var i;
  31705. var j;
  31706. for (i = 0; i <= radialSegments; i++) {
  31707. var modI = i % radialSegments;
  31708. var u = modI / radialSegments * 2 * p * Math.PI;
  31709. var p1 = getPos(u);
  31710. var p2 = getPos(u + 0.01);
  31711. var tang = p2.subtract(p1);
  31712. var n = p2.add(p1);
  31713. var bitan = BABYLON.Vector3.Cross(tang, n);
  31714. n = BABYLON.Vector3.Cross(bitan, tang);
  31715. bitan.normalize();
  31716. n.normalize();
  31717. for (j = 0; j < tubularSegments; j++) {
  31718. var modJ = j % tubularSegments;
  31719. var v = modJ / tubularSegments * 2 * Math.PI;
  31720. var cx = -tube * Math.cos(v);
  31721. var cy = tube * Math.sin(v);
  31722. positions.push(p1.x + cx * n.x + cy * bitan.x);
  31723. positions.push(p1.y + cx * n.y + cy * bitan.y);
  31724. positions.push(p1.z + cx * n.z + cy * bitan.z);
  31725. uvs.push(i / radialSegments);
  31726. uvs.push(j / tubularSegments);
  31727. }
  31728. }
  31729. for (i = 0; i < radialSegments; i++) {
  31730. for (j = 0; j < tubularSegments; j++) {
  31731. var jNext = (j + 1) % tubularSegments;
  31732. var a = i * tubularSegments + j;
  31733. var b = (i + 1) * tubularSegments + j;
  31734. var c = (i + 1) * tubularSegments + jNext;
  31735. var d = i * tubularSegments + jNext;
  31736. indices.push(d);
  31737. indices.push(b);
  31738. indices.push(a);
  31739. indices.push(d);
  31740. indices.push(c);
  31741. indices.push(b);
  31742. }
  31743. }
  31744. // Normals
  31745. VertexData.ComputeNormals(positions, indices, normals);
  31746. // Sides
  31747. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31748. // Result
  31749. var vertexData = new VertexData();
  31750. vertexData.indices = indices;
  31751. vertexData.positions = positions;
  31752. vertexData.normals = normals;
  31753. vertexData.uvs = uvs;
  31754. return vertexData;
  31755. };
  31756. // Tools
  31757. /**
  31758. * @param {any} - positions (number[] or Float32Array)
  31759. * @param {any} - indices (number[] or Uint16Array)
  31760. * @param {any} - normals (number[] or Float32Array)
  31761. */
  31762. VertexData.ComputeNormals = function (positions, indices, normals) {
  31763. var index = 0;
  31764. var p1p2x = 0.0;
  31765. var p1p2y = 0.0;
  31766. var p1p2z = 0.0;
  31767. var p3p2x = 0.0;
  31768. var p3p2y = 0.0;
  31769. var p3p2z = 0.0;
  31770. var faceNormalx = 0.0;
  31771. var faceNormaly = 0.0;
  31772. var faceNormalz = 0.0;
  31773. var length = 0.0;
  31774. var i1 = 0;
  31775. var i2 = 0;
  31776. var i3 = 0;
  31777. for (index = 0; index < positions.length; index++) {
  31778. normals[index] = 0.0;
  31779. }
  31780. // indice triplet = 1 face
  31781. var nbFaces = indices.length / 3;
  31782. for (index = 0; index < nbFaces; index++) {
  31783. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  31784. i2 = indices[index * 3 + 1];
  31785. i3 = indices[index * 3 + 2];
  31786. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  31787. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  31788. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  31789. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  31790. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  31791. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  31792. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  31793. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  31794. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  31795. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31796. length = (length === 0) ? 1.0 : length;
  31797. faceNormalx /= length; // normalize this normal
  31798. faceNormaly /= length;
  31799. faceNormalz /= length;
  31800. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  31801. normals[i1 * 3 + 1] += faceNormaly;
  31802. normals[i1 * 3 + 2] += faceNormalz;
  31803. normals[i2 * 3] += faceNormalx;
  31804. normals[i2 * 3 + 1] += faceNormaly;
  31805. normals[i2 * 3 + 2] += faceNormalz;
  31806. normals[i3 * 3] += faceNormalx;
  31807. normals[i3 * 3 + 1] += faceNormaly;
  31808. normals[i3 * 3 + 2] += faceNormalz;
  31809. }
  31810. // last normalization of each normal
  31811. for (index = 0; index < normals.length / 3; index++) {
  31812. faceNormalx = normals[index * 3];
  31813. faceNormaly = normals[index * 3 + 1];
  31814. faceNormalz = normals[index * 3 + 2];
  31815. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  31816. length = (length === 0) ? 1.0 : length;
  31817. faceNormalx /= length;
  31818. faceNormaly /= length;
  31819. faceNormalz /= length;
  31820. normals[index * 3] = faceNormalx;
  31821. normals[index * 3 + 1] = faceNormaly;
  31822. normals[index * 3 + 2] = faceNormalz;
  31823. }
  31824. };
  31825. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  31826. var li = indices.length;
  31827. var ln = normals.length;
  31828. var i;
  31829. var n;
  31830. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31831. switch (sideOrientation) {
  31832. case BABYLON.Mesh.FRONTSIDE:
  31833. // nothing changed
  31834. break;
  31835. case BABYLON.Mesh.BACKSIDE:
  31836. var tmp;
  31837. // indices
  31838. for (i = 0; i < li; i += 3) {
  31839. tmp = indices[i];
  31840. indices[i] = indices[i + 2];
  31841. indices[i + 2] = tmp;
  31842. }
  31843. // normals
  31844. for (n = 0; n < ln; n++) {
  31845. normals[n] = -normals[n];
  31846. }
  31847. break;
  31848. case BABYLON.Mesh.DOUBLESIDE:
  31849. // positions
  31850. var lp = positions.length;
  31851. var l = lp / 3;
  31852. for (var p = 0; p < lp; p++) {
  31853. positions[lp + p] = positions[p];
  31854. }
  31855. // indices
  31856. for (i = 0; i < li; i += 3) {
  31857. indices[i + li] = indices[i + 2] + l;
  31858. indices[i + 1 + li] = indices[i + 1] + l;
  31859. indices[i + 2 + li] = indices[i] + l;
  31860. }
  31861. // normals
  31862. for (n = 0; n < ln; n++) {
  31863. normals[ln + n] = -normals[n];
  31864. }
  31865. // uvs
  31866. var lu = uvs.length;
  31867. for (var u = 0; u < lu; u++) {
  31868. uvs[u + lu] = uvs[u];
  31869. }
  31870. break;
  31871. }
  31872. };
  31873. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  31874. var vertexData = new VertexData();
  31875. // positions
  31876. var positions = parsedVertexData.positions;
  31877. if (positions) {
  31878. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  31879. }
  31880. // normals
  31881. var normals = parsedVertexData.normals;
  31882. if (normals) {
  31883. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  31884. }
  31885. // uvs
  31886. var uvs = parsedVertexData.uvs;
  31887. if (uvs) {
  31888. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  31889. }
  31890. // uv2s
  31891. var uv2s = parsedVertexData.uv2s;
  31892. if (uv2s) {
  31893. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  31894. }
  31895. // uv3s
  31896. var uv3s = parsedVertexData.uv3s;
  31897. if (uv3s) {
  31898. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  31899. }
  31900. // uv4s
  31901. var uv4s = parsedVertexData.uv4s;
  31902. if (uv4s) {
  31903. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  31904. }
  31905. // uv5s
  31906. var uv5s = parsedVertexData.uv5s;
  31907. if (uv5s) {
  31908. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  31909. }
  31910. // uv6s
  31911. var uv6s = parsedVertexData.uv6s;
  31912. if (uv6s) {
  31913. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  31914. }
  31915. // colors
  31916. var colors = parsedVertexData.colors;
  31917. if (colors) {
  31918. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  31919. }
  31920. // matricesIndices
  31921. var matricesIndices = parsedVertexData.matricesIndices;
  31922. if (matricesIndices) {
  31923. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  31924. }
  31925. // matricesWeights
  31926. var matricesWeights = parsedVertexData.matricesWeights;
  31927. if (matricesWeights) {
  31928. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  31929. }
  31930. // indices
  31931. var indices = parsedVertexData.indices;
  31932. if (indices) {
  31933. vertexData.indices = indices;
  31934. }
  31935. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  31936. };
  31937. return VertexData;
  31938. }());
  31939. BABYLON.VertexData = VertexData;
  31940. })(BABYLON || (BABYLON = {}));
  31941. var BABYLON;
  31942. (function (BABYLON) {
  31943. var Tags = (function () {
  31944. function Tags() {
  31945. }
  31946. Tags.EnableFor = function (obj) {
  31947. obj._tags = obj._tags || {};
  31948. obj.hasTags = function () {
  31949. return Tags.HasTags(obj);
  31950. };
  31951. obj.addTags = function (tagsString) {
  31952. return Tags.AddTagsTo(obj, tagsString);
  31953. };
  31954. obj.removeTags = function (tagsString) {
  31955. return Tags.RemoveTagsFrom(obj, tagsString);
  31956. };
  31957. obj.matchesTagsQuery = function (tagsQuery) {
  31958. return Tags.MatchesQuery(obj, tagsQuery);
  31959. };
  31960. };
  31961. Tags.DisableFor = function (obj) {
  31962. delete obj._tags;
  31963. delete obj.hasTags;
  31964. delete obj.addTags;
  31965. delete obj.removeTags;
  31966. delete obj.matchesTagsQuery;
  31967. };
  31968. Tags.HasTags = function (obj) {
  31969. if (!obj._tags) {
  31970. return false;
  31971. }
  31972. return !BABYLON.Tools.IsEmpty(obj._tags);
  31973. };
  31974. Tags.GetTags = function (obj, asString) {
  31975. if (asString === void 0) { asString = true; }
  31976. if (!obj._tags) {
  31977. return null;
  31978. }
  31979. if (asString) {
  31980. var tagsArray = [];
  31981. for (var tag in obj._tags) {
  31982. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  31983. tagsArray.push(tag);
  31984. }
  31985. }
  31986. return tagsArray.join(" ");
  31987. }
  31988. else {
  31989. return obj._tags;
  31990. }
  31991. };
  31992. // the tags 'true' and 'false' are reserved and cannot be used as tags
  31993. // a tag cannot start with '||', '&&', and '!'
  31994. // it cannot contain whitespaces
  31995. Tags.AddTagsTo = function (obj, tagsString) {
  31996. if (!tagsString) {
  31997. return;
  31998. }
  31999. if (typeof tagsString !== "string") {
  32000. return;
  32001. }
  32002. var tags = tagsString.split(" ");
  32003. for (var t in tags) {
  32004. Tags._AddTagTo(obj, tags[t]);
  32005. }
  32006. };
  32007. Tags._AddTagTo = function (obj, tag) {
  32008. tag = tag.trim();
  32009. if (tag === "" || tag === "true" || tag === "false") {
  32010. return;
  32011. }
  32012. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  32013. return;
  32014. }
  32015. Tags.EnableFor(obj);
  32016. obj._tags[tag] = true;
  32017. };
  32018. Tags.RemoveTagsFrom = function (obj, tagsString) {
  32019. if (!Tags.HasTags(obj)) {
  32020. return;
  32021. }
  32022. var tags = tagsString.split(" ");
  32023. for (var t in tags) {
  32024. Tags._RemoveTagFrom(obj, tags[t]);
  32025. }
  32026. };
  32027. Tags._RemoveTagFrom = function (obj, tag) {
  32028. delete obj._tags[tag];
  32029. };
  32030. Tags.MatchesQuery = function (obj, tagsQuery) {
  32031. if (tagsQuery === undefined) {
  32032. return true;
  32033. }
  32034. if (tagsQuery === "") {
  32035. return Tags.HasTags(obj);
  32036. }
  32037. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  32038. };
  32039. return Tags;
  32040. }());
  32041. BABYLON.Tags = Tags;
  32042. })(BABYLON || (BABYLON = {}));
  32043. var BABYLON;
  32044. (function (BABYLON) {
  32045. var Internals;
  32046. (function (Internals) {
  32047. var AndOrNotEvaluator = (function () {
  32048. function AndOrNotEvaluator() {
  32049. }
  32050. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  32051. if (!query.match(/\([^\(\)]*\)/g)) {
  32052. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  32053. }
  32054. else {
  32055. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  32056. // remove parenthesis
  32057. r = r.slice(1, r.length - 1);
  32058. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  32059. });
  32060. }
  32061. if (query === "true") {
  32062. return true;
  32063. }
  32064. if (query === "false") {
  32065. return false;
  32066. }
  32067. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  32068. };
  32069. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  32070. evaluateCallback = evaluateCallback || (function (r) {
  32071. return r === "true" ? true : false;
  32072. });
  32073. var result;
  32074. var or = parenthesisContent.split("||");
  32075. for (var i in or) {
  32076. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  32077. var and = ori.split("&&");
  32078. if (and.length > 1) {
  32079. for (var j = 0; j < and.length; ++j) {
  32080. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  32081. if (andj !== "true" && andj !== "false") {
  32082. if (andj[0] === "!") {
  32083. result = !evaluateCallback(andj.substring(1));
  32084. }
  32085. else {
  32086. result = evaluateCallback(andj);
  32087. }
  32088. }
  32089. else {
  32090. result = andj === "true" ? true : false;
  32091. }
  32092. if (!result) {
  32093. ori = "false";
  32094. break;
  32095. }
  32096. }
  32097. }
  32098. if (result || ori === "true") {
  32099. result = true;
  32100. break;
  32101. }
  32102. // result equals false (or undefined)
  32103. if (ori !== "true" && ori !== "false") {
  32104. if (ori[0] === "!") {
  32105. result = !evaluateCallback(ori.substring(1));
  32106. }
  32107. else {
  32108. result = evaluateCallback(ori);
  32109. }
  32110. }
  32111. else {
  32112. result = ori === "true" ? true : false;
  32113. }
  32114. }
  32115. // the whole parenthesis scope is replaced by 'true' or 'false'
  32116. return result ? "true" : "false";
  32117. };
  32118. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  32119. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  32120. // remove whitespaces
  32121. r = r.replace(/[\s]/g, function () { return ""; });
  32122. return r.length % 2 ? "!" : "";
  32123. });
  32124. booleanString = booleanString.trim();
  32125. if (booleanString === "!true") {
  32126. booleanString = "false";
  32127. }
  32128. else if (booleanString === "!false") {
  32129. booleanString = "true";
  32130. }
  32131. return booleanString;
  32132. };
  32133. return AndOrNotEvaluator;
  32134. }());
  32135. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  32136. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32137. })(BABYLON || (BABYLON = {}));
  32138. var BABYLON;
  32139. (function (BABYLON) {
  32140. var PostProcessRenderPass = (function () {
  32141. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  32142. this._enabled = true;
  32143. this._refCount = 0;
  32144. this._name = name;
  32145. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  32146. this.setRenderList(renderList);
  32147. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  32148. this._renderTexture.onAfterRenderObservable.add(afterRender);
  32149. this._scene = scene;
  32150. this._renderList = renderList;
  32151. }
  32152. // private
  32153. PostProcessRenderPass.prototype._incRefCount = function () {
  32154. if (this._refCount === 0) {
  32155. this._scene.customRenderTargets.push(this._renderTexture);
  32156. }
  32157. return ++this._refCount;
  32158. };
  32159. PostProcessRenderPass.prototype._decRefCount = function () {
  32160. this._refCount--;
  32161. if (this._refCount <= 0) {
  32162. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  32163. }
  32164. return this._refCount;
  32165. };
  32166. PostProcessRenderPass.prototype._update = function () {
  32167. this.setRenderList(this._renderList);
  32168. };
  32169. // public
  32170. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  32171. this._renderTexture.renderList = renderList;
  32172. };
  32173. PostProcessRenderPass.prototype.getRenderTexture = function () {
  32174. return this._renderTexture;
  32175. };
  32176. return PostProcessRenderPass;
  32177. }());
  32178. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  32179. })(BABYLON || (BABYLON = {}));
  32180. var BABYLON;
  32181. (function (BABYLON) {
  32182. var PostProcessRenderEffect = (function () {
  32183. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  32184. this._engine = engine;
  32185. this._name = name;
  32186. this._singleInstance = singleInstance || true;
  32187. this._getPostProcess = getPostProcess;
  32188. this._cameras = [];
  32189. this._indicesForCamera = [];
  32190. this._postProcesses = {};
  32191. this._renderPasses = {};
  32192. this._renderEffectAsPasses = {};
  32193. }
  32194. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  32195. get: function () {
  32196. for (var index in this._postProcesses) {
  32197. if (!this._postProcesses[index].isSupported) {
  32198. return false;
  32199. }
  32200. }
  32201. return true;
  32202. },
  32203. enumerable: true,
  32204. configurable: true
  32205. });
  32206. PostProcessRenderEffect.prototype._update = function () {
  32207. for (var renderPassName in this._renderPasses) {
  32208. this._renderPasses[renderPassName]._update();
  32209. }
  32210. };
  32211. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  32212. this._renderPasses[renderPass._name] = renderPass;
  32213. this._linkParameters();
  32214. };
  32215. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  32216. delete this._renderPasses[renderPass._name];
  32217. this._linkParameters();
  32218. };
  32219. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  32220. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  32221. this._linkParameters();
  32222. };
  32223. PostProcessRenderEffect.prototype.getPass = function (passName) {
  32224. for (var renderPassName in this._renderPasses) {
  32225. if (renderPassName === passName) {
  32226. return this._renderPasses[passName];
  32227. }
  32228. }
  32229. };
  32230. PostProcessRenderEffect.prototype.emptyPasses = function () {
  32231. this._renderPasses = {};
  32232. this._linkParameters();
  32233. };
  32234. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  32235. var cameraKey;
  32236. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32237. for (var i = 0; i < _cam.length; i++) {
  32238. var camera = _cam[i];
  32239. var cameraName = camera.name;
  32240. if (this._singleInstance) {
  32241. cameraKey = 0;
  32242. }
  32243. else {
  32244. cameraKey = cameraName;
  32245. }
  32246. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  32247. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  32248. if (!this._indicesForCamera[cameraName]) {
  32249. this._indicesForCamera[cameraName] = [];
  32250. }
  32251. this._indicesForCamera[cameraName].push(index);
  32252. if (this._cameras.indexOf(camera) === -1) {
  32253. this._cameras[cameraName] = camera;
  32254. }
  32255. for (var passName in this._renderPasses) {
  32256. this._renderPasses[passName]._incRefCount();
  32257. }
  32258. }
  32259. this._linkParameters();
  32260. };
  32261. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  32262. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32263. for (var i = 0; i < _cam.length; i++) {
  32264. var camera = _cam[i];
  32265. var cameraName = camera.name;
  32266. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32267. var index = this._cameras.indexOf(cameraName);
  32268. this._indicesForCamera.splice(index, 1);
  32269. this._cameras.splice(index, 1);
  32270. for (var passName in this._renderPasses) {
  32271. this._renderPasses[passName]._decRefCount();
  32272. }
  32273. }
  32274. };
  32275. PostProcessRenderEffect.prototype._enable = function (cameras) {
  32276. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32277. for (var i = 0; i < _cam.length; i++) {
  32278. var camera = _cam[i];
  32279. var cameraName = camera.name;
  32280. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  32281. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  32282. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  32283. }
  32284. }
  32285. for (var passName in this._renderPasses) {
  32286. this._renderPasses[passName]._incRefCount();
  32287. }
  32288. }
  32289. };
  32290. PostProcessRenderEffect.prototype._disable = function (cameras) {
  32291. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32292. for (var i = 0; i < _cam.length; i++) {
  32293. var camera = _cam[i];
  32294. var cameraName = camera.Name;
  32295. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  32296. for (var passName in this._renderPasses) {
  32297. this._renderPasses[passName]._decRefCount();
  32298. }
  32299. }
  32300. };
  32301. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  32302. if (this._singleInstance) {
  32303. return this._postProcesses[0];
  32304. }
  32305. else {
  32306. return this._postProcesses[camera.name];
  32307. }
  32308. };
  32309. PostProcessRenderEffect.prototype._linkParameters = function () {
  32310. var _this = this;
  32311. for (var index in this._postProcesses) {
  32312. if (this.applyParameters) {
  32313. this.applyParameters(this._postProcesses[index]);
  32314. }
  32315. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  32316. _this._linkTextures(effect);
  32317. });
  32318. }
  32319. };
  32320. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  32321. for (var renderPassName in this._renderPasses) {
  32322. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  32323. }
  32324. for (var renderEffectName in this._renderEffectAsPasses) {
  32325. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  32326. }
  32327. };
  32328. return PostProcessRenderEffect;
  32329. }());
  32330. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  32331. })(BABYLON || (BABYLON = {}));
  32332. var BABYLON;
  32333. (function (BABYLON) {
  32334. var PostProcessRenderPipeline = (function () {
  32335. function PostProcessRenderPipeline(engine, name) {
  32336. this._engine = engine;
  32337. this._name = name;
  32338. this._renderEffects = {};
  32339. this._renderEffectsForIsolatedPass = {};
  32340. this._cameras = [];
  32341. }
  32342. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  32343. get: function () {
  32344. for (var renderEffectName in this._renderEffects) {
  32345. if (!this._renderEffects[renderEffectName].isSupported) {
  32346. return false;
  32347. }
  32348. }
  32349. return true;
  32350. },
  32351. enumerable: true,
  32352. configurable: true
  32353. });
  32354. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  32355. this._renderEffects[renderEffect._name] = renderEffect;
  32356. };
  32357. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  32358. var renderEffects = this._renderEffects[renderEffectName];
  32359. if (!renderEffects) {
  32360. return;
  32361. }
  32362. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32363. };
  32364. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  32365. var renderEffects = this._renderEffects[renderEffectName];
  32366. if (!renderEffects) {
  32367. return;
  32368. }
  32369. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  32370. };
  32371. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  32372. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32373. var indicesToDelete = [];
  32374. var i;
  32375. for (i = 0; i < _cam.length; i++) {
  32376. var camera = _cam[i];
  32377. var cameraName = camera.name;
  32378. if (this._cameras.indexOf(camera) === -1) {
  32379. this._cameras[cameraName] = camera;
  32380. }
  32381. else if (unique) {
  32382. indicesToDelete.push(i);
  32383. }
  32384. }
  32385. for (i = 0; i < indicesToDelete.length; i++) {
  32386. cameras.splice(indicesToDelete[i], 1);
  32387. }
  32388. for (var renderEffectName in this._renderEffects) {
  32389. this._renderEffects[renderEffectName]._attachCameras(_cam);
  32390. }
  32391. };
  32392. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  32393. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32394. for (var renderEffectName in this._renderEffects) {
  32395. this._renderEffects[renderEffectName]._detachCameras(_cam);
  32396. }
  32397. for (var i = 0; i < _cam.length; i++) {
  32398. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  32399. }
  32400. };
  32401. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  32402. var _this = this;
  32403. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32404. var pass = null;
  32405. var renderEffectName;
  32406. for (renderEffectName in this._renderEffects) {
  32407. pass = this._renderEffects[renderEffectName].getPass(passName);
  32408. if (pass != null) {
  32409. break;
  32410. }
  32411. }
  32412. if (pass === null) {
  32413. return;
  32414. }
  32415. for (renderEffectName in this._renderEffects) {
  32416. this._renderEffects[renderEffectName]._disable(_cam);
  32417. }
  32418. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  32419. for (var i = 0; i < _cam.length; i++) {
  32420. var camera = _cam[i];
  32421. var cameraName = camera.name;
  32422. 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); });
  32423. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  32424. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  32425. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  32426. }
  32427. };
  32428. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  32429. var _this = this;
  32430. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  32431. for (var i = 0; i < _cam.length; i++) {
  32432. var camera = _cam[i];
  32433. var cameraName = camera.name;
  32434. 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); });
  32435. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  32436. }
  32437. for (var renderEffectName in this._renderEffects) {
  32438. this._renderEffects[renderEffectName]._enable(_cam);
  32439. }
  32440. };
  32441. PostProcessRenderPipeline.prototype._update = function () {
  32442. for (var renderEffectName in this._renderEffects) {
  32443. this._renderEffects[renderEffectName]._update();
  32444. }
  32445. for (var i = 0; i < this._cameras.length; i++) {
  32446. var cameraName = this._cameras[i].name;
  32447. if (this._renderEffectsForIsolatedPass[cameraName]) {
  32448. this._renderEffectsForIsolatedPass[cameraName]._update();
  32449. }
  32450. }
  32451. };
  32452. PostProcessRenderPipeline.prototype.dispose = function () {
  32453. // Must be implemented by children
  32454. };
  32455. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  32456. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  32457. return PostProcessRenderPipeline;
  32458. }());
  32459. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  32460. })(BABYLON || (BABYLON = {}));
  32461. var BABYLON;
  32462. (function (BABYLON) {
  32463. var PostProcessRenderPipelineManager = (function () {
  32464. function PostProcessRenderPipelineManager() {
  32465. this._renderPipelines = {};
  32466. }
  32467. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  32468. this._renderPipelines[renderPipeline._name] = renderPipeline;
  32469. };
  32470. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  32471. var renderPipeline = this._renderPipelines[renderPipelineName];
  32472. if (!renderPipeline) {
  32473. return;
  32474. }
  32475. renderPipeline._attachCameras(cameras, unique);
  32476. };
  32477. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  32478. var renderPipeline = this._renderPipelines[renderPipelineName];
  32479. if (!renderPipeline) {
  32480. return;
  32481. }
  32482. renderPipeline._detachCameras(cameras);
  32483. };
  32484. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32485. var renderPipeline = this._renderPipelines[renderPipelineName];
  32486. if (!renderPipeline) {
  32487. return;
  32488. }
  32489. renderPipeline._enableEffect(renderEffectName, cameras);
  32490. };
  32491. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  32492. var renderPipeline = this._renderPipelines[renderPipelineName];
  32493. if (!renderPipeline) {
  32494. return;
  32495. }
  32496. renderPipeline._disableEffect(renderEffectName, cameras);
  32497. };
  32498. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  32499. var renderPipeline = this._renderPipelines[renderPipelineName];
  32500. if (!renderPipeline) {
  32501. return;
  32502. }
  32503. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  32504. };
  32505. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  32506. var renderPipeline = this._renderPipelines[renderPipelineName];
  32507. if (!renderPipeline) {
  32508. return;
  32509. }
  32510. renderPipeline._disableDisplayOnlyPass(cameras);
  32511. };
  32512. PostProcessRenderPipelineManager.prototype.update = function () {
  32513. for (var renderPipelineName in this._renderPipelines) {
  32514. var pipeline = this._renderPipelines[renderPipelineName];
  32515. if (!pipeline.isSupported) {
  32516. pipeline.dispose();
  32517. delete this._renderPipelines[renderPipelineName];
  32518. }
  32519. else {
  32520. pipeline._update();
  32521. }
  32522. }
  32523. };
  32524. return PostProcessRenderPipelineManager;
  32525. }());
  32526. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  32527. })(BABYLON || (BABYLON = {}));
  32528. var BABYLON;
  32529. (function (BABYLON) {
  32530. var BoundingBoxRenderer = (function () {
  32531. function BoundingBoxRenderer(scene) {
  32532. this.frontColor = new BABYLON.Color3(1, 1, 1);
  32533. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  32534. this.showBackLines = true;
  32535. this.renderList = new BABYLON.SmartArray(32);
  32536. this._vertexBuffers = {};
  32537. this._scene = scene;
  32538. }
  32539. BoundingBoxRenderer.prototype._prepareRessources = function () {
  32540. if (this._colorShader) {
  32541. return;
  32542. }
  32543. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  32544. attributes: [BABYLON.VertexBuffer.PositionKind],
  32545. uniforms: ["worldViewProjection", "color"]
  32546. });
  32547. var engine = this._scene.getEngine();
  32548. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  32549. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  32550. this._indexBuffer = engine.createIndexBuffer([0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 7, 1, 6, 2, 5, 3, 4]);
  32551. };
  32552. BoundingBoxRenderer.prototype.reset = function () {
  32553. this.renderList.reset();
  32554. };
  32555. BoundingBoxRenderer.prototype.render = function () {
  32556. if (this.renderList.length === 0) {
  32557. return;
  32558. }
  32559. this._prepareRessources();
  32560. if (!this._colorShader.isReady()) {
  32561. return;
  32562. }
  32563. var engine = this._scene.getEngine();
  32564. engine.setDepthWrite(false);
  32565. this._colorShader._preBind();
  32566. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  32567. var boundingBox = this.renderList.data[boundingBoxIndex];
  32568. var min = boundingBox.minimum;
  32569. var max = boundingBox.maximum;
  32570. var diff = max.subtract(min);
  32571. var median = min.add(diff.scale(0.5));
  32572. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  32573. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  32574. .multiply(boundingBox.getWorldMatrix());
  32575. // VBOs
  32576. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  32577. if (this.showBackLines) {
  32578. // Back
  32579. engine.setDepthFunctionToGreaterOrEqual();
  32580. this._scene.resetCachedMaterial();
  32581. this._colorShader.setColor4("color", this.backColor.toColor4());
  32582. this._colorShader.bind(worldMatrix);
  32583. // Draw order
  32584. engine.draw(false, 0, 24);
  32585. }
  32586. // Front
  32587. engine.setDepthFunctionToLess();
  32588. this._scene.resetCachedMaterial();
  32589. this._colorShader.setColor4("color", this.frontColor.toColor4());
  32590. this._colorShader.bind(worldMatrix);
  32591. // Draw order
  32592. engine.draw(false, 0, 24);
  32593. }
  32594. this._colorShader.unbind();
  32595. engine.setDepthFunctionToLessOrEqual();
  32596. engine.setDepthWrite(true);
  32597. };
  32598. BoundingBoxRenderer.prototype.dispose = function () {
  32599. if (!this._colorShader) {
  32600. return;
  32601. }
  32602. this._colorShader.dispose();
  32603. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32604. if (buffer) {
  32605. buffer.dispose();
  32606. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32607. }
  32608. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32609. };
  32610. return BoundingBoxRenderer;
  32611. }());
  32612. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  32613. })(BABYLON || (BABYLON = {}));
  32614. var BABYLON;
  32615. (function (BABYLON) {
  32616. var Condition = (function () {
  32617. function Condition(actionManager) {
  32618. this._actionManager = actionManager;
  32619. }
  32620. Condition.prototype.isValid = function () {
  32621. return true;
  32622. };
  32623. Condition.prototype._getProperty = function (propertyPath) {
  32624. return this._actionManager._getProperty(propertyPath);
  32625. };
  32626. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  32627. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32628. };
  32629. Condition.prototype.serialize = function () {
  32630. };
  32631. Condition.prototype._serialize = function (serializedCondition) {
  32632. return {
  32633. type: 2,
  32634. children: [],
  32635. name: serializedCondition.name,
  32636. properties: serializedCondition.properties
  32637. };
  32638. };
  32639. return Condition;
  32640. }());
  32641. BABYLON.Condition = Condition;
  32642. var ValueCondition = (function (_super) {
  32643. __extends(ValueCondition, _super);
  32644. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  32645. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  32646. _super.call(this, actionManager);
  32647. this.propertyPath = propertyPath;
  32648. this.value = value;
  32649. this.operator = operator;
  32650. this._target = target;
  32651. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  32652. this._property = this._getProperty(this.propertyPath);
  32653. }
  32654. Object.defineProperty(ValueCondition, "IsEqual", {
  32655. get: function () {
  32656. return ValueCondition._IsEqual;
  32657. },
  32658. enumerable: true,
  32659. configurable: true
  32660. });
  32661. Object.defineProperty(ValueCondition, "IsDifferent", {
  32662. get: function () {
  32663. return ValueCondition._IsDifferent;
  32664. },
  32665. enumerable: true,
  32666. configurable: true
  32667. });
  32668. Object.defineProperty(ValueCondition, "IsGreater", {
  32669. get: function () {
  32670. return ValueCondition._IsGreater;
  32671. },
  32672. enumerable: true,
  32673. configurable: true
  32674. });
  32675. Object.defineProperty(ValueCondition, "IsLesser", {
  32676. get: function () {
  32677. return ValueCondition._IsLesser;
  32678. },
  32679. enumerable: true,
  32680. configurable: true
  32681. });
  32682. // Methods
  32683. ValueCondition.prototype.isValid = function () {
  32684. switch (this.operator) {
  32685. case ValueCondition.IsGreater:
  32686. return this._effectiveTarget[this._property] > this.value;
  32687. case ValueCondition.IsLesser:
  32688. return this._effectiveTarget[this._property] < this.value;
  32689. case ValueCondition.IsEqual:
  32690. case ValueCondition.IsDifferent:
  32691. var check;
  32692. if (this.value.equals) {
  32693. check = this.value.equals(this._effectiveTarget[this._property]);
  32694. }
  32695. else {
  32696. check = this.value === this._effectiveTarget[this._property];
  32697. }
  32698. return this.operator === ValueCondition.IsEqual ? check : !check;
  32699. }
  32700. return false;
  32701. };
  32702. ValueCondition.prototype.serialize = function () {
  32703. return this._serialize({
  32704. name: "ValueCondition",
  32705. properties: [
  32706. BABYLON.Action._GetTargetProperty(this._target),
  32707. { name: "propertyPath", value: this.propertyPath },
  32708. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  32709. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  32710. ]
  32711. });
  32712. };
  32713. ValueCondition.GetOperatorName = function (operator) {
  32714. switch (operator) {
  32715. case ValueCondition._IsEqual: return "IsEqual";
  32716. case ValueCondition._IsDifferent: return "IsDifferent";
  32717. case ValueCondition._IsGreater: return "IsGreater";
  32718. case ValueCondition._IsLesser: return "IsLesser";
  32719. default: return "";
  32720. }
  32721. };
  32722. // Statics
  32723. ValueCondition._IsEqual = 0;
  32724. ValueCondition._IsDifferent = 1;
  32725. ValueCondition._IsGreater = 2;
  32726. ValueCondition._IsLesser = 3;
  32727. return ValueCondition;
  32728. }(Condition));
  32729. BABYLON.ValueCondition = ValueCondition;
  32730. var PredicateCondition = (function (_super) {
  32731. __extends(PredicateCondition, _super);
  32732. function PredicateCondition(actionManager, predicate) {
  32733. _super.call(this, actionManager);
  32734. this.predicate = predicate;
  32735. }
  32736. PredicateCondition.prototype.isValid = function () {
  32737. return this.predicate();
  32738. };
  32739. return PredicateCondition;
  32740. }(Condition));
  32741. BABYLON.PredicateCondition = PredicateCondition;
  32742. var StateCondition = (function (_super) {
  32743. __extends(StateCondition, _super);
  32744. function StateCondition(actionManager, target, value) {
  32745. _super.call(this, actionManager);
  32746. this.value = value;
  32747. this._target = target;
  32748. }
  32749. // Methods
  32750. StateCondition.prototype.isValid = function () {
  32751. return this._target.state === this.value;
  32752. };
  32753. StateCondition.prototype.serialize = function () {
  32754. return this._serialize({
  32755. name: "StateCondition",
  32756. properties: [
  32757. BABYLON.Action._GetTargetProperty(this._target),
  32758. { name: "value", value: this.value }
  32759. ]
  32760. });
  32761. };
  32762. return StateCondition;
  32763. }(Condition));
  32764. BABYLON.StateCondition = StateCondition;
  32765. })(BABYLON || (BABYLON = {}));
  32766. var BABYLON;
  32767. (function (BABYLON) {
  32768. var Action = (function () {
  32769. function Action(triggerOptions, condition) {
  32770. this.triggerOptions = triggerOptions;
  32771. if (triggerOptions.parameter) {
  32772. this.trigger = triggerOptions.trigger;
  32773. this._triggerParameter = triggerOptions.parameter;
  32774. }
  32775. else {
  32776. this.trigger = triggerOptions;
  32777. }
  32778. this._nextActiveAction = this;
  32779. this._condition = condition;
  32780. }
  32781. // Methods
  32782. Action.prototype._prepare = function () {
  32783. };
  32784. Action.prototype.getTriggerParameter = function () {
  32785. return this._triggerParameter;
  32786. };
  32787. Action.prototype._executeCurrent = function (evt) {
  32788. if (this._nextActiveAction._condition) {
  32789. var condition = this._nextActiveAction._condition;
  32790. var currentRenderId = this._actionManager.getScene().getRenderId();
  32791. // We cache the current evaluation for the current frame
  32792. if (condition._evaluationId === currentRenderId) {
  32793. if (!condition._currentResult) {
  32794. return;
  32795. }
  32796. }
  32797. else {
  32798. condition._evaluationId = currentRenderId;
  32799. if (!condition.isValid()) {
  32800. condition._currentResult = false;
  32801. return;
  32802. }
  32803. condition._currentResult = true;
  32804. }
  32805. }
  32806. this._nextActiveAction.execute(evt);
  32807. this.skipToNextActiveAction();
  32808. };
  32809. Action.prototype.execute = function (evt) {
  32810. };
  32811. Action.prototype.skipToNextActiveAction = function () {
  32812. if (this._nextActiveAction._child) {
  32813. if (!this._nextActiveAction._child._actionManager) {
  32814. this._nextActiveAction._child._actionManager = this._actionManager;
  32815. }
  32816. this._nextActiveAction = this._nextActiveAction._child;
  32817. }
  32818. else {
  32819. this._nextActiveAction = this;
  32820. }
  32821. };
  32822. Action.prototype.then = function (action) {
  32823. this._child = action;
  32824. action._actionManager = this._actionManager;
  32825. action._prepare();
  32826. return action;
  32827. };
  32828. Action.prototype._getProperty = function (propertyPath) {
  32829. return this._actionManager._getProperty(propertyPath);
  32830. };
  32831. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  32832. return this._actionManager._getEffectiveTarget(target, propertyPath);
  32833. };
  32834. Action.prototype.serialize = function (parent) {
  32835. };
  32836. // Called by BABYLON.Action objects in serialize(...). Internal use
  32837. Action.prototype._serialize = function (serializedAction, parent) {
  32838. var serializationObject = {
  32839. type: 1,
  32840. children: [],
  32841. name: serializedAction.name,
  32842. properties: serializedAction.properties || []
  32843. };
  32844. // Serialize child
  32845. if (this._child) {
  32846. this._child.serialize(serializationObject);
  32847. }
  32848. // Check if "this" has a condition
  32849. if (this._condition) {
  32850. var serializedCondition = this._condition.serialize();
  32851. serializedCondition.children.push(serializationObject);
  32852. if (parent) {
  32853. parent.children.push(serializedCondition);
  32854. }
  32855. return serializedCondition;
  32856. }
  32857. if (parent) {
  32858. parent.children.push(serializationObject);
  32859. }
  32860. return serializationObject;
  32861. };
  32862. Action._SerializeValueAsString = function (value) {
  32863. if (typeof value === "number") {
  32864. return value.toString();
  32865. }
  32866. if (typeof value === "boolean") {
  32867. return value ? "true" : "false";
  32868. }
  32869. if (value instanceof BABYLON.Vector2) {
  32870. return value.x + ", " + value.y;
  32871. }
  32872. if (value instanceof BABYLON.Vector3) {
  32873. return value.x + ", " + value.y + ", " + value.z;
  32874. }
  32875. if (value instanceof BABYLON.Color3) {
  32876. return value.r + ", " + value.g + ", " + value.b;
  32877. }
  32878. if (value instanceof BABYLON.Color4) {
  32879. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  32880. }
  32881. return value; // string
  32882. };
  32883. Action._GetTargetProperty = function (target) {
  32884. return {
  32885. name: "target",
  32886. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  32887. : target instanceof BABYLON.Light ? "LightProperties"
  32888. : target instanceof BABYLON.Camera ? "CameraProperties"
  32889. : "SceneProperties",
  32890. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  32891. };
  32892. };
  32893. return Action;
  32894. }());
  32895. BABYLON.Action = Action;
  32896. })(BABYLON || (BABYLON = {}));
  32897. var BABYLON;
  32898. (function (BABYLON) {
  32899. /**
  32900. * ActionEvent is the event beint sent when an action is triggered.
  32901. */
  32902. var ActionEvent = (function () {
  32903. /**
  32904. * @constructor
  32905. * @param source The mesh or sprite that triggered the action.
  32906. * @param pointerX The X mouse cursor position at the time of the event
  32907. * @param pointerY The Y mouse cursor position at the time of the event
  32908. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  32909. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  32910. */
  32911. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  32912. this.source = source;
  32913. this.pointerX = pointerX;
  32914. this.pointerY = pointerY;
  32915. this.meshUnderPointer = meshUnderPointer;
  32916. this.sourceEvent = sourceEvent;
  32917. this.additionalData = additionalData;
  32918. }
  32919. /**
  32920. * Helper function to auto-create an ActionEvent from a source mesh.
  32921. * @param source The source mesh that triggered the event
  32922. * @param evt {Event} The original (browser) event
  32923. */
  32924. ActionEvent.CreateNew = function (source, evt, additionalData) {
  32925. var scene = source.getScene();
  32926. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32927. };
  32928. /**
  32929. * Helper function to auto-create an ActionEvent from a source mesh.
  32930. * @param source The source sprite that triggered the event
  32931. * @param scene Scene associated with the sprite
  32932. * @param evt {Event} The original (browser) event
  32933. */
  32934. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  32935. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  32936. };
  32937. /**
  32938. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  32939. * @param scene the scene where the event occurred
  32940. * @param evt {Event} The original (browser) event
  32941. */
  32942. ActionEvent.CreateNewFromScene = function (scene, evt) {
  32943. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  32944. };
  32945. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  32946. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  32947. };
  32948. return ActionEvent;
  32949. }());
  32950. BABYLON.ActionEvent = ActionEvent;
  32951. /**
  32952. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  32953. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  32954. */
  32955. var ActionManager = (function () {
  32956. function ActionManager(scene) {
  32957. // Members
  32958. this.actions = new Array();
  32959. this._scene = scene;
  32960. scene._actionManagers.push(this);
  32961. }
  32962. Object.defineProperty(ActionManager, "NothingTrigger", {
  32963. get: function () {
  32964. return ActionManager._NothingTrigger;
  32965. },
  32966. enumerable: true,
  32967. configurable: true
  32968. });
  32969. Object.defineProperty(ActionManager, "OnPickTrigger", {
  32970. get: function () {
  32971. return ActionManager._OnPickTrigger;
  32972. },
  32973. enumerable: true,
  32974. configurable: true
  32975. });
  32976. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  32977. get: function () {
  32978. return ActionManager._OnLeftPickTrigger;
  32979. },
  32980. enumerable: true,
  32981. configurable: true
  32982. });
  32983. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  32984. get: function () {
  32985. return ActionManager._OnRightPickTrigger;
  32986. },
  32987. enumerable: true,
  32988. configurable: true
  32989. });
  32990. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  32991. get: function () {
  32992. return ActionManager._OnCenterPickTrigger;
  32993. },
  32994. enumerable: true,
  32995. configurable: true
  32996. });
  32997. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  32998. get: function () {
  32999. return ActionManager._OnPickDownTrigger;
  33000. },
  33001. enumerable: true,
  33002. configurable: true
  33003. });
  33004. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  33005. get: function () {
  33006. return ActionManager._OnPickUpTrigger;
  33007. },
  33008. enumerable: true,
  33009. configurable: true
  33010. });
  33011. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  33012. /// This trigger will only be raised if you also declared a OnPickDown
  33013. get: function () {
  33014. return ActionManager._OnPickOutTrigger;
  33015. },
  33016. enumerable: true,
  33017. configurable: true
  33018. });
  33019. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  33020. get: function () {
  33021. return ActionManager._OnLongPressTrigger;
  33022. },
  33023. enumerable: true,
  33024. configurable: true
  33025. });
  33026. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  33027. get: function () {
  33028. return ActionManager._OnPointerOverTrigger;
  33029. },
  33030. enumerable: true,
  33031. configurable: true
  33032. });
  33033. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  33034. get: function () {
  33035. return ActionManager._OnPointerOutTrigger;
  33036. },
  33037. enumerable: true,
  33038. configurable: true
  33039. });
  33040. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  33041. get: function () {
  33042. return ActionManager._OnEveryFrameTrigger;
  33043. },
  33044. enumerable: true,
  33045. configurable: true
  33046. });
  33047. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  33048. get: function () {
  33049. return ActionManager._OnIntersectionEnterTrigger;
  33050. },
  33051. enumerable: true,
  33052. configurable: true
  33053. });
  33054. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  33055. get: function () {
  33056. return ActionManager._OnIntersectionExitTrigger;
  33057. },
  33058. enumerable: true,
  33059. configurable: true
  33060. });
  33061. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  33062. get: function () {
  33063. return ActionManager._OnKeyDownTrigger;
  33064. },
  33065. enumerable: true,
  33066. configurable: true
  33067. });
  33068. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  33069. get: function () {
  33070. return ActionManager._OnKeyUpTrigger;
  33071. },
  33072. enumerable: true,
  33073. configurable: true
  33074. });
  33075. // Methods
  33076. ActionManager.prototype.dispose = function () {
  33077. var index = this._scene._actionManagers.indexOf(this);
  33078. if (index > -1) {
  33079. this._scene._actionManagers.splice(index, 1);
  33080. }
  33081. };
  33082. ActionManager.prototype.getScene = function () {
  33083. return this._scene;
  33084. };
  33085. /**
  33086. * Does this action manager handles actions of any of the given triggers
  33087. * @param {number[]} triggers - the triggers to be tested
  33088. * @return {boolean} whether one (or more) of the triggers is handeled
  33089. */
  33090. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  33091. for (var index = 0; index < this.actions.length; index++) {
  33092. var action = this.actions[index];
  33093. if (triggers.indexOf(action.trigger) > -1) {
  33094. return true;
  33095. }
  33096. }
  33097. return false;
  33098. };
  33099. /**
  33100. * Does this action manager handles actions of a given trigger
  33101. * @param {number} trigger - the trigger to be tested
  33102. * @return {boolean} whether the trigger is handeled
  33103. */
  33104. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  33105. for (var index = 0; index < this.actions.length; index++) {
  33106. var action = this.actions[index];
  33107. if (action.trigger === trigger) {
  33108. return true;
  33109. }
  33110. }
  33111. return false;
  33112. };
  33113. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  33114. /**
  33115. * Does this action manager has pointer triggers
  33116. * @return {boolean} whether or not it has pointer triggers
  33117. */
  33118. get: function () {
  33119. for (var index = 0; index < this.actions.length; index++) {
  33120. var action = this.actions[index];
  33121. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  33122. return true;
  33123. }
  33124. }
  33125. return false;
  33126. },
  33127. enumerable: true,
  33128. configurable: true
  33129. });
  33130. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  33131. /**
  33132. * Does this action manager has pick triggers
  33133. * @return {boolean} whether or not it has pick triggers
  33134. */
  33135. get: function () {
  33136. for (var index = 0; index < this.actions.length; index++) {
  33137. var action = this.actions[index];
  33138. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  33139. return true;
  33140. }
  33141. }
  33142. return false;
  33143. },
  33144. enumerable: true,
  33145. configurable: true
  33146. });
  33147. /**
  33148. * Registers an action to this action manager
  33149. * @param {BABYLON.Action} action - the action to be registered
  33150. * @return {BABYLON.Action} the action amended (prepared) after registration
  33151. */
  33152. ActionManager.prototype.registerAction = function (action) {
  33153. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  33154. if (this.getScene().actionManager !== this) {
  33155. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  33156. return null;
  33157. }
  33158. }
  33159. this.actions.push(action);
  33160. action._actionManager = this;
  33161. action._prepare();
  33162. return action;
  33163. };
  33164. /**
  33165. * Process a specific trigger
  33166. * @param {number} trigger - the trigger to process
  33167. * @param evt {BABYLON.ActionEvent} the event details to be processed
  33168. */
  33169. ActionManager.prototype.processTrigger = function (trigger, evt) {
  33170. for (var index = 0; index < this.actions.length; index++) {
  33171. var action = this.actions[index];
  33172. if (action.trigger === trigger) {
  33173. if (trigger === ActionManager.OnKeyUpTrigger
  33174. || trigger === ActionManager.OnKeyDownTrigger) {
  33175. var parameter = action.getTriggerParameter();
  33176. if (parameter) {
  33177. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  33178. var actualkey = String.fromCharCode(unicode).toLowerCase();
  33179. if (actualkey !== parameter.toLowerCase()) {
  33180. continue;
  33181. }
  33182. }
  33183. }
  33184. action._executeCurrent(evt);
  33185. }
  33186. }
  33187. };
  33188. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  33189. var properties = propertyPath.split(".");
  33190. for (var index = 0; index < properties.length - 1; index++) {
  33191. target = target[properties[index]];
  33192. }
  33193. return target;
  33194. };
  33195. ActionManager.prototype._getProperty = function (propertyPath) {
  33196. var properties = propertyPath.split(".");
  33197. return properties[properties.length - 1];
  33198. };
  33199. ActionManager.prototype.serialize = function (name) {
  33200. var root = {
  33201. children: [],
  33202. name: name,
  33203. type: 3,
  33204. properties: [] // Empty for root but required
  33205. };
  33206. for (var i = 0; i < this.actions.length; i++) {
  33207. var triggerObject = {
  33208. type: 0,
  33209. children: [],
  33210. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  33211. properties: []
  33212. };
  33213. var triggerOptions = this.actions[i].triggerOptions;
  33214. if (triggerOptions && typeof triggerOptions !== "number") {
  33215. if (triggerOptions.parameter instanceof BABYLON.Node) {
  33216. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  33217. }
  33218. else {
  33219. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  33220. }
  33221. }
  33222. // Serialize child action, recursively
  33223. this.actions[i].serialize(triggerObject);
  33224. // Add serialized trigger
  33225. root.children.push(triggerObject);
  33226. }
  33227. return root;
  33228. };
  33229. ActionManager.Parse = function (parsedActions, object, scene) {
  33230. var actionManager = new BABYLON.ActionManager(scene);
  33231. if (object === null)
  33232. scene.actionManager = actionManager;
  33233. else
  33234. object.actionManager = actionManager;
  33235. // instanciate a new object
  33236. var instanciate = function (name, params) {
  33237. var newInstance = Object.create(BABYLON[name].prototype);
  33238. newInstance.constructor.apply(newInstance, params);
  33239. return newInstance;
  33240. };
  33241. var parseParameter = function (name, value, target, propertyPath) {
  33242. if (propertyPath === null) {
  33243. // String, boolean or float
  33244. var floatValue = parseFloat(value);
  33245. if (value === "true" || value === "false")
  33246. return value === "true";
  33247. else
  33248. return isNaN(floatValue) ? value : floatValue;
  33249. }
  33250. var effectiveTarget = propertyPath.split(".");
  33251. var values = value.split(",");
  33252. // Get effective Target
  33253. for (var i = 0; i < effectiveTarget.length; i++) {
  33254. target = target[effectiveTarget[i]];
  33255. }
  33256. // Return appropriate value with its type
  33257. if (typeof (target) === "boolean")
  33258. return values[0] === "true";
  33259. if (typeof (target) === "string")
  33260. return values[0];
  33261. // Parameters with multiple values such as Vector3 etc.
  33262. var split = new Array();
  33263. for (var i = 0; i < values.length; i++)
  33264. split.push(parseFloat(values[i]));
  33265. if (target instanceof BABYLON.Vector3)
  33266. return BABYLON.Vector3.FromArray(split);
  33267. if (target instanceof BABYLON.Vector4)
  33268. return BABYLON.Vector4.FromArray(split);
  33269. if (target instanceof BABYLON.Color3)
  33270. return BABYLON.Color3.FromArray(split);
  33271. if (target instanceof BABYLON.Color4)
  33272. return BABYLON.Color4.FromArray(split);
  33273. return parseFloat(values[0]);
  33274. };
  33275. // traverse graph per trigger
  33276. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  33277. if (combineArray === void 0) { combineArray = null; }
  33278. if (parsedAction.detached)
  33279. return;
  33280. var parameters = new Array();
  33281. var target = null;
  33282. var propertyPath = null;
  33283. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  33284. // Parameters
  33285. if (parsedAction.type === 2)
  33286. parameters.push(actionManager);
  33287. else
  33288. parameters.push(trigger);
  33289. if (combine) {
  33290. var actions = new Array();
  33291. for (var j = 0; j < parsedAction.combine.length; j++) {
  33292. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  33293. }
  33294. parameters.push(actions);
  33295. }
  33296. else {
  33297. for (var i = 0; i < parsedAction.properties.length; i++) {
  33298. var value = parsedAction.properties[i].value;
  33299. var name = parsedAction.properties[i].name;
  33300. var targetType = parsedAction.properties[i].targetType;
  33301. if (name === "target")
  33302. if (targetType !== null && targetType === "SceneProperties")
  33303. value = target = scene;
  33304. else
  33305. value = target = scene.getNodeByName(value);
  33306. else if (name === "parent")
  33307. value = scene.getNodeByName(value);
  33308. else if (name === "sound")
  33309. value = scene.getSoundByName(value);
  33310. else if (name !== "propertyPath") {
  33311. if (parsedAction.type === 2 && name === "operator")
  33312. value = BABYLON.ValueCondition[value];
  33313. else
  33314. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  33315. }
  33316. else {
  33317. propertyPath = value;
  33318. }
  33319. parameters.push(value);
  33320. }
  33321. }
  33322. if (combineArray === null) {
  33323. parameters.push(condition);
  33324. }
  33325. else {
  33326. parameters.push(null);
  33327. }
  33328. // If interpolate value action
  33329. if (parsedAction.name === "InterpolateValueAction") {
  33330. var param = parameters[parameters.length - 2];
  33331. parameters[parameters.length - 1] = param;
  33332. parameters[parameters.length - 2] = condition;
  33333. }
  33334. // Action or condition(s) and not CombineAction
  33335. var newAction = instanciate(parsedAction.name, parameters);
  33336. if (newAction instanceof BABYLON.Condition && condition !== null) {
  33337. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  33338. if (action)
  33339. action.then(nothing);
  33340. else
  33341. actionManager.registerAction(nothing);
  33342. action = nothing;
  33343. }
  33344. if (combineArray === null) {
  33345. if (newAction instanceof BABYLON.Condition) {
  33346. condition = newAction;
  33347. newAction = action;
  33348. }
  33349. else {
  33350. condition = null;
  33351. if (action)
  33352. action.then(newAction);
  33353. else
  33354. actionManager.registerAction(newAction);
  33355. }
  33356. }
  33357. else {
  33358. combineArray.push(newAction);
  33359. }
  33360. for (var i = 0; i < parsedAction.children.length; i++)
  33361. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  33362. };
  33363. // triggers
  33364. for (var i = 0; i < parsedActions.children.length; i++) {
  33365. var triggerParams;
  33366. var trigger = parsedActions.children[i];
  33367. if (trigger.properties.length > 0) {
  33368. var param = trigger.properties[0].value;
  33369. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  33370. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  33371. }
  33372. else
  33373. triggerParams = BABYLON.ActionManager[trigger.name];
  33374. for (var j = 0; j < trigger.children.length; j++) {
  33375. if (!trigger.detached)
  33376. traverse(trigger.children[j], triggerParams, null, null);
  33377. }
  33378. }
  33379. };
  33380. ActionManager.GetTriggerName = function (trigger) {
  33381. switch (trigger) {
  33382. case 0: return "NothingTrigger";
  33383. case 1: return "OnPickTrigger";
  33384. case 2: return "OnLeftPickTrigger";
  33385. case 3: return "OnRightPickTrigger";
  33386. case 4: return "OnCenterPickTrigger";
  33387. case 5: return "OnPickDownTrigger";
  33388. case 6: return "OnPickUpTrigger";
  33389. case 7: return "OnLongPressTrigger";
  33390. case 8: return "OnPointerOverTrigger";
  33391. case 9: return "OnPointerOutTrigger";
  33392. case 10: return "OnEveryFrameTrigger";
  33393. case 11: return "OnIntersectionEnterTrigger";
  33394. case 12: return "OnIntersectionExitTrigger";
  33395. case 13: return "OnKeyDownTrigger";
  33396. case 14: return "OnKeyUpTrigger";
  33397. case 15: return "OnPickOutTrigger";
  33398. default: return "";
  33399. }
  33400. };
  33401. // Statics
  33402. ActionManager._NothingTrigger = 0;
  33403. ActionManager._OnPickTrigger = 1;
  33404. ActionManager._OnLeftPickTrigger = 2;
  33405. ActionManager._OnRightPickTrigger = 3;
  33406. ActionManager._OnCenterPickTrigger = 4;
  33407. ActionManager._OnPickDownTrigger = 5;
  33408. ActionManager._OnPickUpTrigger = 6;
  33409. ActionManager._OnLongPressTrigger = 7;
  33410. ActionManager._OnPointerOverTrigger = 8;
  33411. ActionManager._OnPointerOutTrigger = 9;
  33412. ActionManager._OnEveryFrameTrigger = 10;
  33413. ActionManager._OnIntersectionEnterTrigger = 11;
  33414. ActionManager._OnIntersectionExitTrigger = 12;
  33415. ActionManager._OnKeyDownTrigger = 13;
  33416. ActionManager._OnKeyUpTrigger = 14;
  33417. ActionManager._OnPickOutTrigger = 15;
  33418. ActionManager.DragMovementThreshold = 10; // in pixels
  33419. ActionManager.LongPressDelay = 500; // in milliseconds
  33420. return ActionManager;
  33421. }());
  33422. BABYLON.ActionManager = ActionManager;
  33423. })(BABYLON || (BABYLON = {}));
  33424. var BABYLON;
  33425. (function (BABYLON) {
  33426. var InterpolateValueAction = (function (_super) {
  33427. __extends(InterpolateValueAction, _super);
  33428. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  33429. if (duration === void 0) { duration = 1000; }
  33430. _super.call(this, triggerOptions, condition);
  33431. this.propertyPath = propertyPath;
  33432. this.value = value;
  33433. this.duration = duration;
  33434. this.stopOtherAnimations = stopOtherAnimations;
  33435. this.onInterpolationDone = onInterpolationDone;
  33436. this._target = this._effectiveTarget = target;
  33437. }
  33438. InterpolateValueAction.prototype._prepare = function () {
  33439. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33440. this._property = this._getProperty(this.propertyPath);
  33441. };
  33442. InterpolateValueAction.prototype.execute = function () {
  33443. var scene = this._actionManager.getScene();
  33444. var keys = [
  33445. {
  33446. frame: 0,
  33447. value: this._effectiveTarget[this._property]
  33448. }, {
  33449. frame: 100,
  33450. value: this.value
  33451. }
  33452. ];
  33453. var dataType;
  33454. if (typeof this.value === "number") {
  33455. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  33456. }
  33457. else if (this.value instanceof BABYLON.Color3) {
  33458. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  33459. }
  33460. else if (this.value instanceof BABYLON.Vector3) {
  33461. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  33462. }
  33463. else if (this.value instanceof BABYLON.Matrix) {
  33464. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  33465. }
  33466. else if (this.value instanceof BABYLON.Quaternion) {
  33467. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  33468. }
  33469. else {
  33470. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  33471. return;
  33472. }
  33473. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  33474. animation.setKeys(keys);
  33475. if (this.stopOtherAnimations) {
  33476. scene.stopAnimation(this._effectiveTarget);
  33477. }
  33478. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  33479. };
  33480. InterpolateValueAction.prototype.serialize = function (parent) {
  33481. return _super.prototype._serialize.call(this, {
  33482. name: "InterpolateValueAction",
  33483. properties: [
  33484. BABYLON.Action._GetTargetProperty(this._target),
  33485. { name: "propertyPath", value: this.propertyPath },
  33486. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33487. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  33488. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  33489. ]
  33490. }, parent);
  33491. };
  33492. return InterpolateValueAction;
  33493. }(BABYLON.Action));
  33494. BABYLON.InterpolateValueAction = InterpolateValueAction;
  33495. })(BABYLON || (BABYLON = {}));
  33496. var BABYLON;
  33497. (function (BABYLON) {
  33498. var SwitchBooleanAction = (function (_super) {
  33499. __extends(SwitchBooleanAction, _super);
  33500. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  33501. _super.call(this, triggerOptions, condition);
  33502. this.propertyPath = propertyPath;
  33503. this._target = this._effectiveTarget = target;
  33504. }
  33505. SwitchBooleanAction.prototype._prepare = function () {
  33506. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33507. this._property = this._getProperty(this.propertyPath);
  33508. };
  33509. SwitchBooleanAction.prototype.execute = function () {
  33510. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  33511. };
  33512. SwitchBooleanAction.prototype.serialize = function (parent) {
  33513. return _super.prototype._serialize.call(this, {
  33514. name: "SwitchBooleanAction",
  33515. properties: [
  33516. BABYLON.Action._GetTargetProperty(this._target),
  33517. { name: "propertyPath", value: this.propertyPath }
  33518. ]
  33519. }, parent);
  33520. };
  33521. return SwitchBooleanAction;
  33522. }(BABYLON.Action));
  33523. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  33524. var SetStateAction = (function (_super) {
  33525. __extends(SetStateAction, _super);
  33526. function SetStateAction(triggerOptions, target, value, condition) {
  33527. _super.call(this, triggerOptions, condition);
  33528. this.value = value;
  33529. this._target = target;
  33530. }
  33531. SetStateAction.prototype.execute = function () {
  33532. this._target.state = this.value;
  33533. };
  33534. SetStateAction.prototype.serialize = function (parent) {
  33535. return _super.prototype._serialize.call(this, {
  33536. name: "SetStateAction",
  33537. properties: [
  33538. BABYLON.Action._GetTargetProperty(this._target),
  33539. { name: "value", value: this.value }
  33540. ]
  33541. }, parent);
  33542. };
  33543. return SetStateAction;
  33544. }(BABYLON.Action));
  33545. BABYLON.SetStateAction = SetStateAction;
  33546. var SetValueAction = (function (_super) {
  33547. __extends(SetValueAction, _super);
  33548. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  33549. _super.call(this, triggerOptions, condition);
  33550. this.propertyPath = propertyPath;
  33551. this.value = value;
  33552. this._target = this._effectiveTarget = target;
  33553. }
  33554. SetValueAction.prototype._prepare = function () {
  33555. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33556. this._property = this._getProperty(this.propertyPath);
  33557. };
  33558. SetValueAction.prototype.execute = function () {
  33559. this._effectiveTarget[this._property] = this.value;
  33560. if (this._target.markAsDirty) {
  33561. this._target.markAsDirty(this._property);
  33562. }
  33563. };
  33564. SetValueAction.prototype.serialize = function (parent) {
  33565. return _super.prototype._serialize.call(this, {
  33566. name: "SetValueAction",
  33567. properties: [
  33568. BABYLON.Action._GetTargetProperty(this._target),
  33569. { name: "propertyPath", value: this.propertyPath },
  33570. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33571. ]
  33572. }, parent);
  33573. };
  33574. return SetValueAction;
  33575. }(BABYLON.Action));
  33576. BABYLON.SetValueAction = SetValueAction;
  33577. var IncrementValueAction = (function (_super) {
  33578. __extends(IncrementValueAction, _super);
  33579. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  33580. _super.call(this, triggerOptions, condition);
  33581. this.propertyPath = propertyPath;
  33582. this.value = value;
  33583. this._target = this._effectiveTarget = target;
  33584. }
  33585. IncrementValueAction.prototype._prepare = function () {
  33586. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  33587. this._property = this._getProperty(this.propertyPath);
  33588. if (typeof this._effectiveTarget[this._property] !== "number") {
  33589. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  33590. }
  33591. };
  33592. IncrementValueAction.prototype.execute = function () {
  33593. this._effectiveTarget[this._property] += this.value;
  33594. if (this._target.markAsDirty) {
  33595. this._target.markAsDirty(this._property);
  33596. }
  33597. };
  33598. IncrementValueAction.prototype.serialize = function (parent) {
  33599. return _super.prototype._serialize.call(this, {
  33600. name: "IncrementValueAction",
  33601. properties: [
  33602. BABYLON.Action._GetTargetProperty(this._target),
  33603. { name: "propertyPath", value: this.propertyPath },
  33604. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  33605. ]
  33606. }, parent);
  33607. };
  33608. return IncrementValueAction;
  33609. }(BABYLON.Action));
  33610. BABYLON.IncrementValueAction = IncrementValueAction;
  33611. var PlayAnimationAction = (function (_super) {
  33612. __extends(PlayAnimationAction, _super);
  33613. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  33614. _super.call(this, triggerOptions, condition);
  33615. this.from = from;
  33616. this.to = to;
  33617. this.loop = loop;
  33618. this._target = target;
  33619. }
  33620. PlayAnimationAction.prototype._prepare = function () {
  33621. };
  33622. PlayAnimationAction.prototype.execute = function () {
  33623. var scene = this._actionManager.getScene();
  33624. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  33625. };
  33626. PlayAnimationAction.prototype.serialize = function (parent) {
  33627. return _super.prototype._serialize.call(this, {
  33628. name: "PlayAnimationAction",
  33629. properties: [
  33630. BABYLON.Action._GetTargetProperty(this._target),
  33631. { name: "from", value: String(this.from) },
  33632. { name: "to", value: String(this.to) },
  33633. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  33634. ]
  33635. }, parent);
  33636. };
  33637. return PlayAnimationAction;
  33638. }(BABYLON.Action));
  33639. BABYLON.PlayAnimationAction = PlayAnimationAction;
  33640. var StopAnimationAction = (function (_super) {
  33641. __extends(StopAnimationAction, _super);
  33642. function StopAnimationAction(triggerOptions, target, condition) {
  33643. _super.call(this, triggerOptions, condition);
  33644. this._target = target;
  33645. }
  33646. StopAnimationAction.prototype._prepare = function () {
  33647. };
  33648. StopAnimationAction.prototype.execute = function () {
  33649. var scene = this._actionManager.getScene();
  33650. scene.stopAnimation(this._target);
  33651. };
  33652. StopAnimationAction.prototype.serialize = function (parent) {
  33653. return _super.prototype._serialize.call(this, {
  33654. name: "StopAnimationAction",
  33655. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  33656. }, parent);
  33657. };
  33658. return StopAnimationAction;
  33659. }(BABYLON.Action));
  33660. BABYLON.StopAnimationAction = StopAnimationAction;
  33661. var DoNothingAction = (function (_super) {
  33662. __extends(DoNothingAction, _super);
  33663. function DoNothingAction(triggerOptions, condition) {
  33664. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  33665. _super.call(this, triggerOptions, condition);
  33666. }
  33667. DoNothingAction.prototype.execute = function () {
  33668. };
  33669. DoNothingAction.prototype.serialize = function (parent) {
  33670. return _super.prototype._serialize.call(this, {
  33671. name: "DoNothingAction",
  33672. properties: []
  33673. }, parent);
  33674. };
  33675. return DoNothingAction;
  33676. }(BABYLON.Action));
  33677. BABYLON.DoNothingAction = DoNothingAction;
  33678. var CombineAction = (function (_super) {
  33679. __extends(CombineAction, _super);
  33680. function CombineAction(triggerOptions, children, condition) {
  33681. _super.call(this, triggerOptions, condition);
  33682. this.children = children;
  33683. }
  33684. CombineAction.prototype._prepare = function () {
  33685. for (var index = 0; index < this.children.length; index++) {
  33686. this.children[index]._actionManager = this._actionManager;
  33687. this.children[index]._prepare();
  33688. }
  33689. };
  33690. CombineAction.prototype.execute = function (evt) {
  33691. for (var index = 0; index < this.children.length; index++) {
  33692. this.children[index].execute(evt);
  33693. }
  33694. };
  33695. CombineAction.prototype.serialize = function (parent) {
  33696. var serializationObject = _super.prototype._serialize.call(this, {
  33697. name: "CombineAction",
  33698. properties: [],
  33699. combine: []
  33700. }, parent);
  33701. for (var i = 0; i < this.children.length; i++) {
  33702. serializationObject.combine.push(this.children[i].serialize(null));
  33703. }
  33704. return serializationObject;
  33705. };
  33706. return CombineAction;
  33707. }(BABYLON.Action));
  33708. BABYLON.CombineAction = CombineAction;
  33709. var ExecuteCodeAction = (function (_super) {
  33710. __extends(ExecuteCodeAction, _super);
  33711. function ExecuteCodeAction(triggerOptions, func, condition) {
  33712. _super.call(this, triggerOptions, condition);
  33713. this.func = func;
  33714. }
  33715. ExecuteCodeAction.prototype.execute = function (evt) {
  33716. this.func(evt);
  33717. };
  33718. return ExecuteCodeAction;
  33719. }(BABYLON.Action));
  33720. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  33721. var SetParentAction = (function (_super) {
  33722. __extends(SetParentAction, _super);
  33723. function SetParentAction(triggerOptions, target, parent, condition) {
  33724. _super.call(this, triggerOptions, condition);
  33725. this._target = target;
  33726. this._parent = parent;
  33727. }
  33728. SetParentAction.prototype._prepare = function () {
  33729. };
  33730. SetParentAction.prototype.execute = function () {
  33731. if (this._target.parent === this._parent) {
  33732. return;
  33733. }
  33734. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  33735. invertParentWorldMatrix.invert();
  33736. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  33737. this._target.parent = this._parent;
  33738. };
  33739. SetParentAction.prototype.serialize = function (parent) {
  33740. return _super.prototype._serialize.call(this, {
  33741. name: "SetParentAction",
  33742. properties: [
  33743. BABYLON.Action._GetTargetProperty(this._target),
  33744. BABYLON.Action._GetTargetProperty(this._parent),
  33745. ]
  33746. }, parent);
  33747. };
  33748. return SetParentAction;
  33749. }(BABYLON.Action));
  33750. BABYLON.SetParentAction = SetParentAction;
  33751. var PlaySoundAction = (function (_super) {
  33752. __extends(PlaySoundAction, _super);
  33753. function PlaySoundAction(triggerOptions, sound, condition) {
  33754. _super.call(this, triggerOptions, condition);
  33755. this._sound = sound;
  33756. }
  33757. PlaySoundAction.prototype._prepare = function () {
  33758. };
  33759. PlaySoundAction.prototype.execute = function () {
  33760. if (this._sound !== undefined)
  33761. this._sound.play();
  33762. };
  33763. PlaySoundAction.prototype.serialize = function (parent) {
  33764. return _super.prototype._serialize.call(this, {
  33765. name: "PlaySoundAction",
  33766. properties: [{ name: "sound", value: this._sound.name }]
  33767. }, parent);
  33768. };
  33769. return PlaySoundAction;
  33770. }(BABYLON.Action));
  33771. BABYLON.PlaySoundAction = PlaySoundAction;
  33772. var StopSoundAction = (function (_super) {
  33773. __extends(StopSoundAction, _super);
  33774. function StopSoundAction(triggerOptions, sound, condition) {
  33775. _super.call(this, triggerOptions, condition);
  33776. this._sound = sound;
  33777. }
  33778. StopSoundAction.prototype._prepare = function () {
  33779. };
  33780. StopSoundAction.prototype.execute = function () {
  33781. if (this._sound !== undefined)
  33782. this._sound.stop();
  33783. };
  33784. StopSoundAction.prototype.serialize = function (parent) {
  33785. return _super.prototype._serialize.call(this, {
  33786. name: "StopSoundAction",
  33787. properties: [{ name: "sound", value: this._sound.name }]
  33788. }, parent);
  33789. };
  33790. return StopSoundAction;
  33791. }(BABYLON.Action));
  33792. BABYLON.StopSoundAction = StopSoundAction;
  33793. })(BABYLON || (BABYLON = {}));
  33794. var BABYLON;
  33795. (function (BABYLON) {
  33796. var Geometry = (function () {
  33797. function Geometry(id, scene, vertexData, updatable, mesh) {
  33798. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  33799. this._totalVertices = 0;
  33800. this._isDisposed = false;
  33801. this.id = id;
  33802. this._engine = scene.getEngine();
  33803. this._meshes = [];
  33804. this._scene = scene;
  33805. //Init vertex buffer cache
  33806. this._vertexBuffers = {};
  33807. this._indices = [];
  33808. // vertexData
  33809. if (vertexData) {
  33810. this.setAllVerticesData(vertexData, updatable);
  33811. }
  33812. else {
  33813. this._totalVertices = 0;
  33814. this._indices = [];
  33815. }
  33816. // applyToMesh
  33817. if (mesh) {
  33818. if (mesh instanceof BABYLON.LinesMesh) {
  33819. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  33820. this.updateExtend();
  33821. }
  33822. this.applyToMesh(mesh);
  33823. mesh.computeWorldMatrix(true);
  33824. }
  33825. }
  33826. Object.defineProperty(Geometry.prototype, "boundingBias", {
  33827. /**
  33828. * 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
  33829. * @returns The Bias Vector
  33830. */
  33831. get: function () {
  33832. return this._boundingBias;
  33833. },
  33834. set: function (value) {
  33835. if (this._boundingBias && this._boundingBias.equals(value)) {
  33836. return;
  33837. }
  33838. this._boundingBias = value.clone();
  33839. this.updateBoundingInfo(true, null);
  33840. },
  33841. enumerable: true,
  33842. configurable: true
  33843. });
  33844. Object.defineProperty(Geometry.prototype, "extend", {
  33845. get: function () {
  33846. return this._extend;
  33847. },
  33848. enumerable: true,
  33849. configurable: true
  33850. });
  33851. Geometry.prototype.getScene = function () {
  33852. return this._scene;
  33853. };
  33854. Geometry.prototype.getEngine = function () {
  33855. return this._engine;
  33856. };
  33857. Geometry.prototype.isReady = function () {
  33858. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  33859. };
  33860. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  33861. vertexData.applyToGeometry(this, updatable);
  33862. this.notifyUpdate();
  33863. };
  33864. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  33865. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  33866. this.setVerticesBuffer(buffer);
  33867. };
  33868. Geometry.prototype.setVerticesBuffer = function (buffer) {
  33869. var kind = buffer.getKind();
  33870. if (this._vertexBuffers[kind]) {
  33871. this._vertexBuffers[kind].dispose();
  33872. }
  33873. this._vertexBuffers[kind] = buffer;
  33874. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33875. var data = buffer.getData();
  33876. var stride = buffer.getStrideSize();
  33877. this._totalVertices = data.length / stride;
  33878. this.updateExtend(data, stride);
  33879. var meshes = this._meshes;
  33880. var numOfMeshes = meshes.length;
  33881. for (var index = 0; index < numOfMeshes; index++) {
  33882. var mesh = meshes[index];
  33883. mesh._resetPointsArrayCache();
  33884. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33885. mesh._createGlobalSubMesh();
  33886. mesh.computeWorldMatrix(true);
  33887. }
  33888. }
  33889. this.notifyUpdate(kind);
  33890. };
  33891. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  33892. var vertexBuffer = this.getVertexBuffer(kind);
  33893. if (!vertexBuffer) {
  33894. return;
  33895. }
  33896. vertexBuffer.updateDirectly(data, offset);
  33897. this.notifyUpdate(kind);
  33898. };
  33899. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  33900. var vertexBuffer = this.getVertexBuffer(kind);
  33901. if (!vertexBuffer) {
  33902. return;
  33903. }
  33904. vertexBuffer.update(data);
  33905. if (kind === BABYLON.VertexBuffer.PositionKind) {
  33906. var stride = vertexBuffer.getStrideSize();
  33907. this._totalVertices = data.length / stride;
  33908. this.updateBoundingInfo(updateExtends, data);
  33909. }
  33910. this.notifyUpdate(kind);
  33911. };
  33912. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  33913. if (updateExtends) {
  33914. this.updateExtend(data);
  33915. }
  33916. var meshes = this._meshes;
  33917. var numOfMeshes = meshes.length;
  33918. for (var index = 0; index < numOfMeshes; index++) {
  33919. var mesh = meshes[index];
  33920. mesh._resetPointsArrayCache();
  33921. if (updateExtends) {
  33922. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  33923. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  33924. var subMesh = mesh.subMeshes[subIndex];
  33925. subMesh.refreshBoundingInfo();
  33926. }
  33927. }
  33928. }
  33929. };
  33930. Geometry.prototype.getTotalVertices = function () {
  33931. if (!this.isReady()) {
  33932. return 0;
  33933. }
  33934. return this._totalVertices;
  33935. };
  33936. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  33937. var vertexBuffer = this.getVertexBuffer(kind);
  33938. if (!vertexBuffer) {
  33939. return null;
  33940. }
  33941. var orig = vertexBuffer.getData();
  33942. if (!copyWhenShared || this._meshes.length === 1) {
  33943. return orig;
  33944. }
  33945. else {
  33946. var len = orig.length;
  33947. var copy = [];
  33948. for (var i = 0; i < len; i++) {
  33949. copy.push(orig[i]);
  33950. }
  33951. return copy;
  33952. }
  33953. };
  33954. Geometry.prototype.getVertexBuffer = function (kind) {
  33955. if (!this.isReady()) {
  33956. return null;
  33957. }
  33958. return this._vertexBuffers[kind];
  33959. };
  33960. Geometry.prototype.getVertexBuffers = function () {
  33961. if (!this.isReady()) {
  33962. return null;
  33963. }
  33964. return this._vertexBuffers;
  33965. };
  33966. Geometry.prototype.isVerticesDataPresent = function (kind) {
  33967. if (!this._vertexBuffers) {
  33968. if (this._delayInfo) {
  33969. return this._delayInfo.indexOf(kind) !== -1;
  33970. }
  33971. return false;
  33972. }
  33973. return this._vertexBuffers[kind] !== undefined;
  33974. };
  33975. Geometry.prototype.getVerticesDataKinds = function () {
  33976. var result = [];
  33977. var kind;
  33978. if (!this._vertexBuffers && this._delayInfo) {
  33979. for (kind in this._delayInfo) {
  33980. result.push(kind);
  33981. }
  33982. }
  33983. else {
  33984. for (kind in this._vertexBuffers) {
  33985. result.push(kind);
  33986. }
  33987. }
  33988. return result;
  33989. };
  33990. Geometry.prototype.setIndices = function (indices, totalVertices) {
  33991. if (this._indexBuffer) {
  33992. this._engine._releaseBuffer(this._indexBuffer);
  33993. }
  33994. this._indices = indices;
  33995. if (this._meshes.length !== 0 && this._indices) {
  33996. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  33997. }
  33998. if (totalVertices !== undefined) {
  33999. this._totalVertices = totalVertices;
  34000. }
  34001. var meshes = this._meshes;
  34002. var numOfMeshes = meshes.length;
  34003. for (var index = 0; index < numOfMeshes; index++) {
  34004. meshes[index]._createGlobalSubMesh();
  34005. }
  34006. this.notifyUpdate();
  34007. };
  34008. Geometry.prototype.getTotalIndices = function () {
  34009. if (!this.isReady()) {
  34010. return 0;
  34011. }
  34012. return this._indices.length;
  34013. };
  34014. Geometry.prototype.getIndices = function (copyWhenShared) {
  34015. if (!this.isReady()) {
  34016. return null;
  34017. }
  34018. var orig = this._indices;
  34019. if (!copyWhenShared || this._meshes.length === 1) {
  34020. return orig;
  34021. }
  34022. else {
  34023. var len = orig.length;
  34024. var copy = [];
  34025. for (var i = 0; i < len; i++) {
  34026. copy.push(orig[i]);
  34027. }
  34028. return copy;
  34029. }
  34030. };
  34031. Geometry.prototype.getIndexBuffer = function () {
  34032. if (!this.isReady()) {
  34033. return null;
  34034. }
  34035. return this._indexBuffer;
  34036. };
  34037. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34038. var meshes = this._meshes;
  34039. var index = meshes.indexOf(mesh);
  34040. if (index === -1) {
  34041. return;
  34042. }
  34043. for (var kind in this._vertexBuffers) {
  34044. this._vertexBuffers[kind].dispose();
  34045. }
  34046. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  34047. this._indexBuffer = null;
  34048. }
  34049. meshes.splice(index, 1);
  34050. mesh._geometry = null;
  34051. if (meshes.length === 0 && shouldDispose) {
  34052. this.dispose();
  34053. }
  34054. };
  34055. Geometry.prototype.applyToMesh = function (mesh) {
  34056. if (mesh._geometry === this) {
  34057. return;
  34058. }
  34059. var previousGeometry = mesh._geometry;
  34060. if (previousGeometry) {
  34061. previousGeometry.releaseForMesh(mesh);
  34062. }
  34063. var meshes = this._meshes;
  34064. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34065. mesh._geometry = this;
  34066. this._scene.pushGeometry(this);
  34067. meshes.push(mesh);
  34068. if (this.isReady()) {
  34069. this._applyToMesh(mesh);
  34070. }
  34071. else {
  34072. mesh._boundingInfo = this._boundingInfo;
  34073. }
  34074. };
  34075. Geometry.prototype.updateExtend = function (data, stride) {
  34076. if (data === void 0) { data = null; }
  34077. if (!data) {
  34078. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34079. }
  34080. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34081. };
  34082. Geometry.prototype._applyToMesh = function (mesh) {
  34083. var numOfMeshes = this._meshes.length;
  34084. // vertexBuffers
  34085. for (var kind in this._vertexBuffers) {
  34086. if (numOfMeshes === 1) {
  34087. this._vertexBuffers[kind].create();
  34088. }
  34089. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  34090. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34091. mesh._resetPointsArrayCache();
  34092. if (!this._extend) {
  34093. this.updateExtend(this._vertexBuffers[kind].getData());
  34094. }
  34095. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34096. mesh._createGlobalSubMesh();
  34097. //bounding info was just created again, world matrix should be applied again.
  34098. mesh._updateBoundingInfo();
  34099. }
  34100. }
  34101. // indexBuffer
  34102. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34103. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34104. }
  34105. if (this._indexBuffer) {
  34106. this._indexBuffer.references = numOfMeshes;
  34107. }
  34108. };
  34109. Geometry.prototype.notifyUpdate = function (kind) {
  34110. if (this.onGeometryUpdated) {
  34111. this.onGeometryUpdated(this, kind);
  34112. }
  34113. };
  34114. Geometry.prototype.load = function (scene, onLoaded) {
  34115. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34116. return;
  34117. }
  34118. if (this.isReady()) {
  34119. if (onLoaded) {
  34120. onLoaded();
  34121. }
  34122. return;
  34123. }
  34124. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34125. this._queueLoad(scene, onLoaded);
  34126. };
  34127. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34128. var _this = this;
  34129. scene._addPendingData(this);
  34130. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  34131. _this._delayLoadingFunction(JSON.parse(data), _this);
  34132. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34133. _this._delayInfo = [];
  34134. scene._removePendingData(_this);
  34135. var meshes = _this._meshes;
  34136. var numOfMeshes = meshes.length;
  34137. for (var index = 0; index < numOfMeshes; index++) {
  34138. _this._applyToMesh(meshes[index]);
  34139. }
  34140. if (onLoaded) {
  34141. onLoaded();
  34142. }
  34143. }, function () { }, scene.database);
  34144. };
  34145. /**
  34146. * Invert the geometry to move from a right handed system to a left handed one.
  34147. */
  34148. Geometry.prototype.toLeftHanded = function () {
  34149. // Flip faces
  34150. var tIndices = this.getIndices(false);
  34151. if (tIndices != null && tIndices.length > 0) {
  34152. for (var i = 0; i < tIndices.length; i += 3) {
  34153. var tTemp = tIndices[i + 0];
  34154. tIndices[i + 0] = tIndices[i + 2];
  34155. tIndices[i + 2] = tTemp;
  34156. }
  34157. this.setIndices(tIndices);
  34158. }
  34159. // Negate position.z
  34160. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34161. if (tPositions != null && tPositions.length > 0) {
  34162. for (var i = 0; i < tPositions.length; i += 3) {
  34163. tPositions[i + 2] = -tPositions[i + 2];
  34164. }
  34165. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34166. }
  34167. // Negate normal.z
  34168. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34169. if (tNormals != null && tNormals.length > 0) {
  34170. for (var i = 0; i < tNormals.length; i += 3) {
  34171. tNormals[i + 2] = -tNormals[i + 2];
  34172. }
  34173. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34174. }
  34175. };
  34176. Geometry.prototype.isDisposed = function () {
  34177. return this._isDisposed;
  34178. };
  34179. Geometry.prototype.dispose = function () {
  34180. var meshes = this._meshes;
  34181. var numOfMeshes = meshes.length;
  34182. var index;
  34183. for (index = 0; index < numOfMeshes; index++) {
  34184. this.releaseForMesh(meshes[index]);
  34185. }
  34186. this._meshes = [];
  34187. for (var kind in this._vertexBuffers) {
  34188. this._vertexBuffers[kind].dispose();
  34189. }
  34190. this._vertexBuffers = {};
  34191. this._totalVertices = 0;
  34192. if (this._indexBuffer) {
  34193. this._engine._releaseBuffer(this._indexBuffer);
  34194. }
  34195. this._indexBuffer = null;
  34196. this._indices = [];
  34197. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34198. this.delayLoadingFile = null;
  34199. this._delayLoadingFunction = null;
  34200. this._delayInfo = [];
  34201. this._boundingInfo = null;
  34202. this._scene.removeGeometry(this);
  34203. this._isDisposed = true;
  34204. };
  34205. Geometry.prototype.copy = function (id) {
  34206. var vertexData = new BABYLON.VertexData();
  34207. vertexData.indices = [];
  34208. var indices = this.getIndices();
  34209. for (var index = 0; index < indices.length; index++) {
  34210. vertexData.indices.push(indices[index]);
  34211. }
  34212. var updatable = false;
  34213. var stopChecking = false;
  34214. var kind;
  34215. for (kind in this._vertexBuffers) {
  34216. // using slice() to make a copy of the array and not just reference it
  34217. var data = this.getVerticesData(kind);
  34218. if (data instanceof Float32Array) {
  34219. vertexData.set(new Float32Array(data), kind);
  34220. }
  34221. else {
  34222. vertexData.set(data.slice(0), kind);
  34223. }
  34224. if (!stopChecking) {
  34225. updatable = this.getVertexBuffer(kind).isUpdatable();
  34226. stopChecking = !updatable;
  34227. }
  34228. }
  34229. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  34230. geometry.delayLoadState = this.delayLoadState;
  34231. geometry.delayLoadingFile = this.delayLoadingFile;
  34232. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34233. for (kind in this._delayInfo) {
  34234. geometry._delayInfo = geometry._delayInfo || [];
  34235. geometry._delayInfo.push(kind);
  34236. }
  34237. // Bounding info
  34238. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34239. return geometry;
  34240. };
  34241. Geometry.prototype.serialize = function () {
  34242. var serializationObject = {};
  34243. serializationObject.id = this.id;
  34244. if (BABYLON.Tags.HasTags(this)) {
  34245. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34246. }
  34247. return serializationObject;
  34248. };
  34249. Geometry.prototype.serializeVerticeData = function () {
  34250. var serializationObject = this.serialize();
  34251. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34252. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34253. }
  34254. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34255. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34256. }
  34257. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34258. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34259. }
  34260. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34261. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  34262. }
  34263. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34264. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  34265. }
  34266. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34267. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  34268. }
  34269. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34270. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  34271. }
  34272. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34273. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  34274. }
  34275. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34276. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  34277. }
  34278. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34279. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34280. serializationObject.matricesIndices._isExpanded = true;
  34281. }
  34282. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34283. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34284. }
  34285. serializationObject.indices = this.getIndices();
  34286. return serializationObject;
  34287. };
  34288. // Statics
  34289. Geometry.ExtractFromMesh = function (mesh, id) {
  34290. var geometry = mesh._geometry;
  34291. if (!geometry) {
  34292. return null;
  34293. }
  34294. return geometry.copy(id);
  34295. };
  34296. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  34297. // be aware Math.random() could cause collisions
  34298. Geometry.RandomId = function () {
  34299. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  34300. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  34301. return v.toString(16);
  34302. });
  34303. };
  34304. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  34305. var scene = mesh.getScene();
  34306. // Geometry
  34307. var geometryId = parsedGeometry.geometryId;
  34308. if (geometryId) {
  34309. var geometry = scene.getGeometryByID(geometryId);
  34310. if (geometry) {
  34311. geometry.applyToMesh(mesh);
  34312. }
  34313. }
  34314. else if (parsedGeometry instanceof ArrayBuffer) {
  34315. var binaryInfo = mesh._binaryInfo;
  34316. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  34317. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  34318. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  34319. }
  34320. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  34321. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  34322. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  34323. }
  34324. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  34325. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  34326. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  34327. }
  34328. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  34329. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  34330. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  34331. }
  34332. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  34333. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  34334. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  34335. }
  34336. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  34337. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  34338. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  34339. }
  34340. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  34341. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  34342. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  34343. }
  34344. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  34345. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  34346. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  34347. }
  34348. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  34349. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  34350. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  34351. }
  34352. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  34353. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  34354. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  34355. }
  34356. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  34357. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  34358. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  34359. }
  34360. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  34361. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  34362. mesh.setIndices(indicesData);
  34363. }
  34364. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  34365. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  34366. mesh.subMeshes = [];
  34367. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  34368. var materialIndex = subMeshesData[(i * 5) + 0];
  34369. var verticesStart = subMeshesData[(i * 5) + 1];
  34370. var verticesCount = subMeshesData[(i * 5) + 2];
  34371. var indexStart = subMeshesData[(i * 5) + 3];
  34372. var indexCount = subMeshesData[(i * 5) + 4];
  34373. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  34374. }
  34375. }
  34376. }
  34377. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  34378. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  34379. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  34380. if (parsedGeometry.uvs) {
  34381. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  34382. }
  34383. if (parsedGeometry.uvs2) {
  34384. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  34385. }
  34386. if (parsedGeometry.uvs3) {
  34387. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  34388. }
  34389. if (parsedGeometry.uvs4) {
  34390. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  34391. }
  34392. if (parsedGeometry.uvs5) {
  34393. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  34394. }
  34395. if (parsedGeometry.uvs6) {
  34396. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  34397. }
  34398. if (parsedGeometry.colors) {
  34399. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  34400. }
  34401. if (parsedGeometry.matricesIndices) {
  34402. if (!parsedGeometry.matricesIndices._isExpanded) {
  34403. var floatIndices = [];
  34404. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  34405. var matricesIndex = parsedGeometry.matricesIndices[i];
  34406. floatIndices.push(matricesIndex & 0x000000FF);
  34407. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34408. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34409. floatIndices.push(matricesIndex >> 24);
  34410. }
  34411. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  34412. }
  34413. else {
  34414. delete parsedGeometry.matricesIndices._isExpanded;
  34415. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  34416. }
  34417. }
  34418. if (parsedGeometry.matricesIndicesExtra) {
  34419. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  34420. var floatIndices = [];
  34421. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  34422. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  34423. floatIndices.push(matricesIndex & 0x000000FF);
  34424. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  34425. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  34426. floatIndices.push(matricesIndex >> 24);
  34427. }
  34428. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  34429. }
  34430. else {
  34431. delete parsedGeometry.matricesIndices._isExpanded;
  34432. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  34433. }
  34434. }
  34435. if (parsedGeometry.matricesWeights) {
  34436. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  34437. }
  34438. if (parsedGeometry.matricesWeightsExtra) {
  34439. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  34440. }
  34441. mesh.setIndices(parsedGeometry.indices);
  34442. }
  34443. // SubMeshes
  34444. if (parsedGeometry.subMeshes) {
  34445. mesh.subMeshes = [];
  34446. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  34447. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  34448. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  34449. }
  34450. }
  34451. // Flat shading
  34452. if (mesh._shouldGenerateFlatShading) {
  34453. mesh.convertToFlatShadedMesh();
  34454. delete mesh._shouldGenerateFlatShading;
  34455. }
  34456. // Update
  34457. mesh.computeWorldMatrix(true);
  34458. // Octree
  34459. if (scene['_selectionOctree']) {
  34460. scene['_selectionOctree'].addMesh(mesh);
  34461. }
  34462. };
  34463. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  34464. if (scene.getGeometryByID(parsedVertexData.id)) {
  34465. return null; // null since geometry could be something else than a box...
  34466. }
  34467. var geometry = new Geometry(parsedVertexData.id, scene);
  34468. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  34469. if (parsedVertexData.delayLoadingFile) {
  34470. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34471. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  34472. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  34473. geometry._delayInfo = [];
  34474. if (parsedVertexData.hasUVs) {
  34475. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34476. }
  34477. if (parsedVertexData.hasUVs2) {
  34478. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34479. }
  34480. if (parsedVertexData.hasUVs3) {
  34481. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34482. }
  34483. if (parsedVertexData.hasUVs4) {
  34484. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34485. }
  34486. if (parsedVertexData.hasUVs5) {
  34487. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34488. }
  34489. if (parsedVertexData.hasUVs6) {
  34490. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34491. }
  34492. if (parsedVertexData.hasColors) {
  34493. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34494. }
  34495. if (parsedVertexData.hasMatricesIndices) {
  34496. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34497. }
  34498. if (parsedVertexData.hasMatricesWeights) {
  34499. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34500. }
  34501. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  34502. }
  34503. else {
  34504. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  34505. }
  34506. scene.pushGeometry(geometry, true);
  34507. return geometry;
  34508. };
  34509. return Geometry;
  34510. }());
  34511. BABYLON.Geometry = Geometry;
  34512. /////// Primitives //////////////////////////////////////////////
  34513. var Geometry;
  34514. (function (Geometry) {
  34515. var Primitives;
  34516. (function (Primitives) {
  34517. /// Abstract class
  34518. var _Primitive = (function (_super) {
  34519. __extends(_Primitive, _super);
  34520. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  34521. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  34522. this._canBeRegenerated = _canBeRegenerated;
  34523. this._beingRegenerated = true;
  34524. this.regenerate();
  34525. this._beingRegenerated = false;
  34526. }
  34527. _Primitive.prototype.canBeRegenerated = function () {
  34528. return this._canBeRegenerated;
  34529. };
  34530. _Primitive.prototype.regenerate = function () {
  34531. if (!this._canBeRegenerated) {
  34532. return;
  34533. }
  34534. this._beingRegenerated = true;
  34535. this.setAllVerticesData(this._regenerateVertexData(), false);
  34536. this._beingRegenerated = false;
  34537. };
  34538. _Primitive.prototype.asNewGeometry = function (id) {
  34539. return _super.prototype.copy.call(this, id);
  34540. };
  34541. // overrides
  34542. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  34543. if (!this._beingRegenerated) {
  34544. return;
  34545. }
  34546. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  34547. };
  34548. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  34549. if (!this._beingRegenerated) {
  34550. return;
  34551. }
  34552. _super.prototype.setVerticesData.call(this, kind, data, false);
  34553. };
  34554. // to override
  34555. // protected
  34556. _Primitive.prototype._regenerateVertexData = function () {
  34557. throw new Error("Abstract method");
  34558. };
  34559. _Primitive.prototype.copy = function (id) {
  34560. throw new Error("Must be overriden in sub-classes.");
  34561. };
  34562. _Primitive.prototype.serialize = function () {
  34563. var serializationObject = _super.prototype.serialize.call(this);
  34564. serializationObject.canBeRegenerated = this.canBeRegenerated();
  34565. return serializationObject;
  34566. };
  34567. return _Primitive;
  34568. }(Geometry));
  34569. Primitives._Primitive = _Primitive;
  34570. var Ribbon = (function (_super) {
  34571. __extends(Ribbon, _super);
  34572. // Members
  34573. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  34574. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34575. _super.call(this, id, scene, canBeRegenerated, mesh);
  34576. this.pathArray = pathArray;
  34577. this.closeArray = closeArray;
  34578. this.closePath = closePath;
  34579. this.offset = offset;
  34580. this.side = side;
  34581. }
  34582. Ribbon.prototype._regenerateVertexData = function () {
  34583. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  34584. };
  34585. Ribbon.prototype.copy = function (id) {
  34586. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  34587. };
  34588. return Ribbon;
  34589. }(_Primitive));
  34590. Primitives.Ribbon = Ribbon;
  34591. var Box = (function (_super) {
  34592. __extends(Box, _super);
  34593. // Members
  34594. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  34595. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34596. _super.call(this, id, scene, canBeRegenerated, mesh);
  34597. this.size = size;
  34598. this.side = side;
  34599. }
  34600. Box.prototype._regenerateVertexData = function () {
  34601. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  34602. };
  34603. Box.prototype.copy = function (id) {
  34604. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34605. };
  34606. Box.prototype.serialize = function () {
  34607. var serializationObject = _super.prototype.serialize.call(this);
  34608. serializationObject.size = this.size;
  34609. return serializationObject;
  34610. };
  34611. Box.Parse = function (parsedBox, scene) {
  34612. if (scene.getGeometryByID(parsedBox.id)) {
  34613. return null; // null since geometry could be something else than a box...
  34614. }
  34615. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  34616. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  34617. scene.pushGeometry(box, true);
  34618. return box;
  34619. };
  34620. return Box;
  34621. }(_Primitive));
  34622. Primitives.Box = Box;
  34623. var Sphere = (function (_super) {
  34624. __extends(Sphere, _super);
  34625. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  34626. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34627. _super.call(this, id, scene, canBeRegenerated, mesh);
  34628. this.segments = segments;
  34629. this.diameter = diameter;
  34630. this.side = side;
  34631. }
  34632. Sphere.prototype._regenerateVertexData = function () {
  34633. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  34634. };
  34635. Sphere.prototype.copy = function (id) {
  34636. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  34637. };
  34638. Sphere.prototype.serialize = function () {
  34639. var serializationObject = _super.prototype.serialize.call(this);
  34640. serializationObject.segments = this.segments;
  34641. serializationObject.diameter = this.diameter;
  34642. return serializationObject;
  34643. };
  34644. Sphere.Parse = function (parsedSphere, scene) {
  34645. if (scene.getGeometryByID(parsedSphere.id)) {
  34646. return null; // null since geometry could be something else than a sphere...
  34647. }
  34648. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  34649. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  34650. scene.pushGeometry(sphere, true);
  34651. return sphere;
  34652. };
  34653. return Sphere;
  34654. }(_Primitive));
  34655. Primitives.Sphere = Sphere;
  34656. var Disc = (function (_super) {
  34657. __extends(Disc, _super);
  34658. // Members
  34659. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  34660. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34661. _super.call(this, id, scene, canBeRegenerated, mesh);
  34662. this.radius = radius;
  34663. this.tessellation = tessellation;
  34664. this.side = side;
  34665. }
  34666. Disc.prototype._regenerateVertexData = function () {
  34667. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  34668. };
  34669. Disc.prototype.copy = function (id) {
  34670. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  34671. };
  34672. return Disc;
  34673. }(_Primitive));
  34674. Primitives.Disc = Disc;
  34675. var Cylinder = (function (_super) {
  34676. __extends(Cylinder, _super);
  34677. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  34678. if (subdivisions === void 0) { subdivisions = 1; }
  34679. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34680. _super.call(this, id, scene, canBeRegenerated, mesh);
  34681. this.height = height;
  34682. this.diameterTop = diameterTop;
  34683. this.diameterBottom = diameterBottom;
  34684. this.tessellation = tessellation;
  34685. this.subdivisions = subdivisions;
  34686. this.side = side;
  34687. }
  34688. Cylinder.prototype._regenerateVertexData = function () {
  34689. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  34690. };
  34691. Cylinder.prototype.copy = function (id) {
  34692. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  34693. };
  34694. Cylinder.prototype.serialize = function () {
  34695. var serializationObject = _super.prototype.serialize.call(this);
  34696. serializationObject.height = this.height;
  34697. serializationObject.diameterTop = this.diameterTop;
  34698. serializationObject.diameterBottom = this.diameterBottom;
  34699. serializationObject.tessellation = this.tessellation;
  34700. return serializationObject;
  34701. };
  34702. Cylinder.Parse = function (parsedCylinder, scene) {
  34703. if (scene.getGeometryByID(parsedCylinder.id)) {
  34704. return null; // null since geometry could be something else than a cylinder...
  34705. }
  34706. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  34707. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  34708. scene.pushGeometry(cylinder, true);
  34709. return cylinder;
  34710. };
  34711. return Cylinder;
  34712. }(_Primitive));
  34713. Primitives.Cylinder = Cylinder;
  34714. var Torus = (function (_super) {
  34715. __extends(Torus, _super);
  34716. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  34717. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34718. _super.call(this, id, scene, canBeRegenerated, mesh);
  34719. this.diameter = diameter;
  34720. this.thickness = thickness;
  34721. this.tessellation = tessellation;
  34722. this.side = side;
  34723. }
  34724. Torus.prototype._regenerateVertexData = function () {
  34725. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  34726. };
  34727. Torus.prototype.copy = function (id) {
  34728. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  34729. };
  34730. Torus.prototype.serialize = function () {
  34731. var serializationObject = _super.prototype.serialize.call(this);
  34732. serializationObject.diameter = this.diameter;
  34733. serializationObject.thickness = this.thickness;
  34734. serializationObject.tessellation = this.tessellation;
  34735. return serializationObject;
  34736. };
  34737. Torus.Parse = function (parsedTorus, scene) {
  34738. if (scene.getGeometryByID(parsedTorus.id)) {
  34739. return null; // null since geometry could be something else than a torus...
  34740. }
  34741. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  34742. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  34743. scene.pushGeometry(torus, true);
  34744. return torus;
  34745. };
  34746. return Torus;
  34747. }(_Primitive));
  34748. Primitives.Torus = Torus;
  34749. var Ground = (function (_super) {
  34750. __extends(Ground, _super);
  34751. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  34752. _super.call(this, id, scene, canBeRegenerated, mesh);
  34753. this.width = width;
  34754. this.height = height;
  34755. this.subdivisions = subdivisions;
  34756. }
  34757. Ground.prototype._regenerateVertexData = function () {
  34758. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  34759. };
  34760. Ground.prototype.copy = function (id) {
  34761. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  34762. };
  34763. Ground.prototype.serialize = function () {
  34764. var serializationObject = _super.prototype.serialize.call(this);
  34765. serializationObject.width = this.width;
  34766. serializationObject.height = this.height;
  34767. serializationObject.subdivisions = this.subdivisions;
  34768. return serializationObject;
  34769. };
  34770. Ground.Parse = function (parsedGround, scene) {
  34771. if (scene.getGeometryByID(parsedGround.id)) {
  34772. return null; // null since geometry could be something else than a ground...
  34773. }
  34774. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  34775. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  34776. scene.pushGeometry(ground, true);
  34777. return ground;
  34778. };
  34779. return Ground;
  34780. }(_Primitive));
  34781. Primitives.Ground = Ground;
  34782. var TiledGround = (function (_super) {
  34783. __extends(TiledGround, _super);
  34784. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  34785. _super.call(this, id, scene, canBeRegenerated, mesh);
  34786. this.xmin = xmin;
  34787. this.zmin = zmin;
  34788. this.xmax = xmax;
  34789. this.zmax = zmax;
  34790. this.subdivisions = subdivisions;
  34791. this.precision = precision;
  34792. }
  34793. TiledGround.prototype._regenerateVertexData = function () {
  34794. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  34795. };
  34796. TiledGround.prototype.copy = function (id) {
  34797. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  34798. };
  34799. return TiledGround;
  34800. }(_Primitive));
  34801. Primitives.TiledGround = TiledGround;
  34802. var Plane = (function (_super) {
  34803. __extends(Plane, _super);
  34804. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  34805. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34806. _super.call(this, id, scene, canBeRegenerated, mesh);
  34807. this.size = size;
  34808. this.side = side;
  34809. }
  34810. Plane.prototype._regenerateVertexData = function () {
  34811. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  34812. };
  34813. Plane.prototype.copy = function (id) {
  34814. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  34815. };
  34816. Plane.prototype.serialize = function () {
  34817. var serializationObject = _super.prototype.serialize.call(this);
  34818. serializationObject.size = this.size;
  34819. return serializationObject;
  34820. };
  34821. Plane.Parse = function (parsedPlane, scene) {
  34822. if (scene.getGeometryByID(parsedPlane.id)) {
  34823. return null; // null since geometry could be something else than a ground...
  34824. }
  34825. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  34826. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  34827. scene.pushGeometry(plane, true);
  34828. return plane;
  34829. };
  34830. return Plane;
  34831. }(_Primitive));
  34832. Primitives.Plane = Plane;
  34833. var TorusKnot = (function (_super) {
  34834. __extends(TorusKnot, _super);
  34835. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  34836. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  34837. _super.call(this, id, scene, canBeRegenerated, mesh);
  34838. this.radius = radius;
  34839. this.tube = tube;
  34840. this.radialSegments = radialSegments;
  34841. this.tubularSegments = tubularSegments;
  34842. this.p = p;
  34843. this.q = q;
  34844. this.side = side;
  34845. }
  34846. TorusKnot.prototype._regenerateVertexData = function () {
  34847. 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 });
  34848. };
  34849. TorusKnot.prototype.copy = function (id) {
  34850. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  34851. };
  34852. TorusKnot.prototype.serialize = function () {
  34853. var serializationObject = _super.prototype.serialize.call(this);
  34854. serializationObject.radius = this.radius;
  34855. serializationObject.tube = this.tube;
  34856. serializationObject.radialSegments = this.radialSegments;
  34857. serializationObject.tubularSegments = this.tubularSegments;
  34858. serializationObject.p = this.p;
  34859. serializationObject.q = this.q;
  34860. return serializationObject;
  34861. };
  34862. ;
  34863. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  34864. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  34865. return null; // null since geometry could be something else than a ground...
  34866. }
  34867. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  34868. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  34869. scene.pushGeometry(torusKnot, true);
  34870. return torusKnot;
  34871. };
  34872. return TorusKnot;
  34873. }(_Primitive));
  34874. Primitives.TorusKnot = TorusKnot;
  34875. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  34876. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  34877. })(BABYLON || (BABYLON = {}));
  34878. var BABYLON;
  34879. (function (BABYLON) {
  34880. var GroundMesh = (function (_super) {
  34881. __extends(GroundMesh, _super);
  34882. function GroundMesh(name, scene) {
  34883. _super.call(this, name, scene);
  34884. this.generateOctree = false;
  34885. this._worldInverse = new BABYLON.Matrix();
  34886. }
  34887. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  34888. get: function () {
  34889. return this._subdivisions;
  34890. },
  34891. enumerable: true,
  34892. configurable: true
  34893. });
  34894. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  34895. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  34896. this._subdivisions = chunksCount;
  34897. this.subdivide(this._subdivisions);
  34898. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  34899. };
  34900. /**
  34901. * Returns a height (y) value in the Worl system :
  34902. * the ground altitude at the coordinates (x, z) expressed in the World system.
  34903. * Returns the ground y position if (x, z) are outside the ground surface.
  34904. * Not pertinent if the ground is rotated.
  34905. */
  34906. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  34907. // express x and y in the ground local system
  34908. x -= this.position.x;
  34909. z -= this.position.z;
  34910. x /= this.scaling.x;
  34911. z /= this.scaling.z;
  34912. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34913. return this.position.y;
  34914. }
  34915. if (!this._heightQuads || this._heightQuads.length == 0) {
  34916. this._initHeightQuads();
  34917. this._computeHeightQuads();
  34918. }
  34919. var facet = this._getFacetAt(x, z);
  34920. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  34921. // return y in the World system
  34922. return y * this.scaling.y + this.position.y;
  34923. };
  34924. /**
  34925. * Returns a normalized vector (Vector3) orthogonal to the ground
  34926. * at the ground coordinates (x, z) expressed in the World system.
  34927. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  34928. * Not pertinent if the ground is rotated.
  34929. */
  34930. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  34931. var normal = new BABYLON.Vector3(0, 1, 0);
  34932. this.getNormalAtCoordinatesToRef(x, z, normal);
  34933. return normal;
  34934. };
  34935. /**
  34936. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  34937. * at the ground coordinates (x, z) expressed in the World system.
  34938. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  34939. * Not pertinent if the ground is rotated.
  34940. */
  34941. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  34942. // express x and y in the ground local system
  34943. x -= this.position.x;
  34944. z -= this.position.z;
  34945. x /= this.scaling.x;
  34946. z /= this.scaling.z;
  34947. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  34948. return;
  34949. }
  34950. if (!this._heightQuads || this._heightQuads.length == 0) {
  34951. this._initHeightQuads();
  34952. this._computeHeightQuads();
  34953. }
  34954. var facet = this._getFacetAt(x, z);
  34955. ref.x = facet.x;
  34956. ref.y = facet.y;
  34957. ref.z = facet.z;
  34958. };
  34959. /**
  34960. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  34961. * if the ground has been updated.
  34962. * This can be used in the render loop
  34963. */
  34964. GroundMesh.prototype.updateCoordinateHeights = function () {
  34965. if (!this._heightQuads || this._heightQuads.length == 0) {
  34966. this._initHeightQuads();
  34967. }
  34968. this._computeHeightQuads();
  34969. };
  34970. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  34971. GroundMesh.prototype._getFacetAt = function (x, z) {
  34972. // retrieve col and row from x, z coordinates in the ground local system
  34973. var col = Math.floor((x + this._maxX) * this._subdivisions / this._width);
  34974. var row = Math.floor(-(z + this._maxZ) * this._subdivisions / this._height + this._subdivisions);
  34975. var quad = this._heightQuads[row * this._subdivisions + col];
  34976. var facet;
  34977. if (z < quad.slope.x * x + quad.slope.y) {
  34978. facet = quad.facet1;
  34979. }
  34980. else {
  34981. facet = quad.facet2;
  34982. }
  34983. return facet;
  34984. };
  34985. // Creates and populates the heightMap array with "facet" elements :
  34986. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  34987. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  34988. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  34989. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  34990. GroundMesh.prototype._initHeightQuads = function () {
  34991. this._heightQuads = new Array();
  34992. for (var row = 0; row < this._subdivisions; row++) {
  34993. for (var col = 0; col < this._subdivisions; col++) {
  34994. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  34995. this._heightQuads[row * this._subdivisions + col] = quad;
  34996. }
  34997. }
  34998. };
  34999. // Compute each quad element values and update the the heightMap array :
  35000. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  35001. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  35002. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  35003. GroundMesh.prototype._computeHeightQuads = function () {
  35004. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35005. var v1 = BABYLON.Tmp.Vector3[3];
  35006. var v2 = BABYLON.Tmp.Vector3[2];
  35007. var v3 = BABYLON.Tmp.Vector3[1];
  35008. var v4 = BABYLON.Tmp.Vector3[0];
  35009. var v1v2 = BABYLON.Tmp.Vector3[4];
  35010. var v1v3 = BABYLON.Tmp.Vector3[5];
  35011. var v1v4 = BABYLON.Tmp.Vector3[6];
  35012. var norm1 = BABYLON.Tmp.Vector3[7];
  35013. var norm2 = BABYLON.Tmp.Vector3[8];
  35014. var i = 0;
  35015. var j = 0;
  35016. var k = 0;
  35017. var cd = 0; // 2D slope coefficient : z = cd * x + h
  35018. var h = 0;
  35019. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  35020. var d2 = 0;
  35021. for (var row = 0; row < this._subdivisions; row++) {
  35022. for (var col = 0; col < this._subdivisions; col++) {
  35023. i = col * 3;
  35024. j = row * (this._subdivisions + 1) * 3;
  35025. k = (row + 1) * (this._subdivisions + 1) * 3;
  35026. v1.x = positions[j + i];
  35027. v1.y = positions[j + i + 1];
  35028. v1.z = positions[j + i + 2];
  35029. v2.x = positions[j + i + 3];
  35030. v2.y = positions[j + i + 4];
  35031. v2.z = positions[j + i + 5];
  35032. v3.x = positions[k + i];
  35033. v3.y = positions[k + i + 1];
  35034. v3.z = positions[k + i + 2];
  35035. v4.x = positions[k + i + 3];
  35036. v4.y = positions[k + i + 4];
  35037. v4.z = positions[k + i + 5];
  35038. // 2D slope V1V4
  35039. cd = (v4.z - v1.z) / (v4.x - v1.x);
  35040. h = v1.z - cd * v1.x; // v1 belongs to the slope
  35041. // facet equations :
  35042. // we compute each facet normal vector
  35043. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  35044. // we compute the value d by applying the equation to v1 which belongs to the plane
  35045. // then we store the facet equation in a Vector4
  35046. v2.subtractToRef(v1, v1v2);
  35047. v3.subtractToRef(v1, v1v3);
  35048. v4.subtractToRef(v1, v1v4);
  35049. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  35050. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  35051. norm1.normalize();
  35052. norm2.normalize();
  35053. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  35054. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  35055. var quad = this._heightQuads[row * this._subdivisions + col];
  35056. quad.slope.copyFromFloats(cd, h);
  35057. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  35058. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  35059. }
  35060. }
  35061. };
  35062. return GroundMesh;
  35063. }(BABYLON.Mesh));
  35064. BABYLON.GroundMesh = GroundMesh;
  35065. })(BABYLON || (BABYLON = {}));
  35066. var BABYLON;
  35067. (function (BABYLON) {
  35068. var LinesMesh = (function (_super) {
  35069. __extends(LinesMesh, _super);
  35070. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  35071. if (parent === void 0) { parent = null; }
  35072. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  35073. this.color = new BABYLON.Color3(1, 1, 1);
  35074. this.alpha = 1;
  35075. this._positionBuffer = {};
  35076. if (source) {
  35077. this.color = source.color.clone();
  35078. this.alpha = source.alpha;
  35079. }
  35080. this._intersectionThreshold = 0.1;
  35081. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  35082. attributes: [BABYLON.VertexBuffer.PositionKind],
  35083. uniforms: ["worldViewProjection", "color"],
  35084. needAlphaBlending: true
  35085. });
  35086. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  35087. }
  35088. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  35089. /**
  35090. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35091. * This margin is expressed in world space coordinates, so its value may vary.
  35092. * Default value is 0.1
  35093. * @returns the intersection Threshold value.
  35094. */
  35095. get: function () {
  35096. return this._intersectionThreshold;
  35097. },
  35098. /**
  35099. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  35100. * This margin is expressed in world space coordinates, so its value may vary.
  35101. * @param value the new threshold to apply
  35102. */
  35103. set: function (value) {
  35104. if (this._intersectionThreshold === value) {
  35105. return;
  35106. }
  35107. this._intersectionThreshold = value;
  35108. if (this.geometry) {
  35109. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  35110. }
  35111. },
  35112. enumerable: true,
  35113. configurable: true
  35114. });
  35115. Object.defineProperty(LinesMesh.prototype, "material", {
  35116. get: function () {
  35117. return this._colorShader;
  35118. },
  35119. enumerable: true,
  35120. configurable: true
  35121. });
  35122. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  35123. get: function () {
  35124. return false;
  35125. },
  35126. enumerable: true,
  35127. configurable: true
  35128. });
  35129. LinesMesh.prototype.createInstance = function (name) {
  35130. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  35131. return null;
  35132. };
  35133. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  35134. var engine = this.getScene().getEngine();
  35135. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  35136. // VBOs
  35137. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  35138. // Color
  35139. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  35140. };
  35141. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  35142. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  35143. return;
  35144. }
  35145. var engine = this.getScene().getEngine();
  35146. // Draw order
  35147. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  35148. };
  35149. LinesMesh.prototype.dispose = function (doNotRecurse) {
  35150. this._colorShader.dispose();
  35151. _super.prototype.dispose.call(this, doNotRecurse);
  35152. };
  35153. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  35154. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  35155. };
  35156. return LinesMesh;
  35157. }(BABYLON.Mesh));
  35158. BABYLON.LinesMesh = LinesMesh;
  35159. })(BABYLON || (BABYLON = {}));
  35160. var BABYLON;
  35161. (function (BABYLON) {
  35162. var DefaultLoadingScreen = (function () {
  35163. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  35164. var _this = this;
  35165. if (_loadingText === void 0) { _loadingText = ""; }
  35166. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  35167. this._renderingCanvas = _renderingCanvas;
  35168. this._loadingText = _loadingText;
  35169. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  35170. // Resize
  35171. this._resizeLoadingUI = function () {
  35172. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  35173. _this._loadingDiv.style.position = "absolute";
  35174. _this._loadingDiv.style.left = canvasRect.left + "px";
  35175. _this._loadingDiv.style.top = canvasRect.top + "px";
  35176. _this._loadingDiv.style.width = canvasRect.width + "px";
  35177. _this._loadingDiv.style.height = canvasRect.height + "px";
  35178. };
  35179. }
  35180. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  35181. var _this = this;
  35182. if (this._loadingDiv) {
  35183. // Do not add a loading screen if there is already one
  35184. return;
  35185. }
  35186. this._loadingDiv = document.createElement("div");
  35187. this._loadingDiv.id = "babylonjsLoadingDiv";
  35188. this._loadingDiv.style.opacity = "0";
  35189. this._loadingDiv.style.transition = "opacity 1.5s ease";
  35190. // Loading text
  35191. this._loadingTextDiv = document.createElement("div");
  35192. this._loadingTextDiv.style.position = "absolute";
  35193. this._loadingTextDiv.style.left = "0";
  35194. this._loadingTextDiv.style.top = "50%";
  35195. this._loadingTextDiv.style.marginTop = "80px";
  35196. this._loadingTextDiv.style.width = "100%";
  35197. this._loadingTextDiv.style.height = "20px";
  35198. this._loadingTextDiv.style.fontFamily = "Arial";
  35199. this._loadingTextDiv.style.fontSize = "14px";
  35200. this._loadingTextDiv.style.color = "white";
  35201. this._loadingTextDiv.style.textAlign = "center";
  35202. this._loadingTextDiv.innerHTML = "Loading";
  35203. this._loadingDiv.appendChild(this._loadingTextDiv);
  35204. //set the predefined text
  35205. this._loadingTextDiv.innerHTML = this._loadingText;
  35206. // Loading img
  35207. var imgBack = new Image();
  35208. 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==";
  35209. imgBack.style.position = "absolute";
  35210. imgBack.style.left = "50%";
  35211. imgBack.style.top = "50%";
  35212. imgBack.style.marginLeft = "-50px";
  35213. imgBack.style.marginTop = "-50px";
  35214. imgBack.style.transition = "transform 1.0s ease";
  35215. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  35216. var deg = 360;
  35217. var onTransitionEnd = function () {
  35218. deg += 360;
  35219. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  35220. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  35221. };
  35222. imgBack.addEventListener("transitionend", onTransitionEnd);
  35223. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  35224. this._loadingDiv.appendChild(imgBack);
  35225. // front image
  35226. var imgFront = new Image();
  35227. 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=";
  35228. imgFront.style.position = "absolute";
  35229. imgFront.style.left = "50%";
  35230. imgFront.style.top = "50%";
  35231. imgFront.style.marginLeft = "-50px";
  35232. imgFront.style.marginTop = "-50px";
  35233. this._loadingDiv.appendChild(imgFront);
  35234. this._resizeLoadingUI();
  35235. window.addEventListener("resize", this._resizeLoadingUI);
  35236. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35237. document.body.appendChild(this._loadingDiv);
  35238. setTimeout(function () {
  35239. _this._loadingDiv.style.opacity = "1";
  35240. imgBack.style.transform = "rotateZ(360deg)";
  35241. imgBack.style.webkitTransform = "rotateZ(360deg)";
  35242. }, 0);
  35243. };
  35244. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  35245. var _this = this;
  35246. if (!this._loadingDiv) {
  35247. return;
  35248. }
  35249. var onTransitionEnd = function () {
  35250. if (!_this._loadingDiv) {
  35251. return;
  35252. }
  35253. document.body.removeChild(_this._loadingDiv);
  35254. window.removeEventListener("resize", _this._resizeLoadingUI);
  35255. _this._loadingDiv = null;
  35256. };
  35257. this._loadingDiv.style.opacity = "0";
  35258. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  35259. };
  35260. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  35261. set: function (text) {
  35262. this._loadingText = text;
  35263. if (this._loadingTextDiv) {
  35264. this._loadingTextDiv.innerHTML = this._loadingText;
  35265. }
  35266. },
  35267. enumerable: true,
  35268. configurable: true
  35269. });
  35270. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  35271. get: function () {
  35272. return this._loadingDivBackgroundColor;
  35273. },
  35274. set: function (color) {
  35275. this._loadingDivBackgroundColor = color;
  35276. if (!this._loadingDiv) {
  35277. return;
  35278. }
  35279. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  35280. },
  35281. enumerable: true,
  35282. configurable: true
  35283. });
  35284. return DefaultLoadingScreen;
  35285. }());
  35286. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  35287. })(BABYLON || (BABYLON = {}));
  35288. var BABYLON;
  35289. (function (BABYLON) {
  35290. var AudioEngine = (function () {
  35291. function AudioEngine() {
  35292. this._audioContext = null;
  35293. this._audioContextInitialized = false;
  35294. this.canUseWebAudio = false;
  35295. this.WarnedWebAudioUnsupported = false;
  35296. this.unlocked = false;
  35297. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  35298. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  35299. this.canUseWebAudio = true;
  35300. }
  35301. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  35302. this._unlockiOSaudio();
  35303. }
  35304. else {
  35305. this.unlocked = true;
  35306. }
  35307. }
  35308. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  35309. get: function () {
  35310. if (!this._audioContextInitialized) {
  35311. this._initializeAudioContext();
  35312. }
  35313. return this._audioContext;
  35314. },
  35315. enumerable: true,
  35316. configurable: true
  35317. });
  35318. AudioEngine.prototype._unlockiOSaudio = function () {
  35319. var _this = this;
  35320. var unlockaudio = function () {
  35321. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  35322. var source = _this.audioContext.createBufferSource();
  35323. source.buffer = buffer;
  35324. source.connect(_this.audioContext.destination);
  35325. source.start(0);
  35326. setTimeout(function () {
  35327. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  35328. _this.unlocked = true;
  35329. window.removeEventListener('touchend', unlockaudio, false);
  35330. if (_this.onAudioUnlocked) {
  35331. _this.onAudioUnlocked();
  35332. }
  35333. }
  35334. }, 0);
  35335. };
  35336. window.addEventListener('touchend', unlockaudio, false);
  35337. };
  35338. AudioEngine.prototype._initializeAudioContext = function () {
  35339. try {
  35340. if (this.canUseWebAudio) {
  35341. this._audioContext = new AudioContext();
  35342. // create a global volume gain node
  35343. this.masterGain = this._audioContext.createGain();
  35344. this.masterGain.gain.value = 1;
  35345. this.masterGain.connect(this._audioContext.destination);
  35346. this._audioContextInitialized = true;
  35347. }
  35348. }
  35349. catch (e) {
  35350. this.canUseWebAudio = false;
  35351. BABYLON.Tools.Error("Web Audio: " + e.message);
  35352. }
  35353. };
  35354. AudioEngine.prototype.dispose = function () {
  35355. if (this.canUseWebAudio && this._audioContextInitialized) {
  35356. if (this._connectedAnalyser) {
  35357. this._connectedAnalyser.stopDebugCanvas();
  35358. this._connectedAnalyser.dispose();
  35359. this.masterGain.disconnect();
  35360. this.masterGain.connect(this._audioContext.destination);
  35361. this._connectedAnalyser = null;
  35362. }
  35363. this.masterGain.gain.value = 1;
  35364. }
  35365. this.WarnedWebAudioUnsupported = false;
  35366. };
  35367. AudioEngine.prototype.getGlobalVolume = function () {
  35368. if (this.canUseWebAudio && this._audioContextInitialized) {
  35369. return this.masterGain.gain.value;
  35370. }
  35371. else {
  35372. return -1;
  35373. }
  35374. };
  35375. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  35376. if (this.canUseWebAudio && this._audioContextInitialized) {
  35377. this.masterGain.gain.value = newVolume;
  35378. }
  35379. };
  35380. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  35381. if (this._connectedAnalyser) {
  35382. this._connectedAnalyser.stopDebugCanvas();
  35383. }
  35384. if (this.canUseWebAudio && this._audioContextInitialized) {
  35385. this._connectedAnalyser = analyser;
  35386. this.masterGain.disconnect();
  35387. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  35388. }
  35389. };
  35390. return AudioEngine;
  35391. }());
  35392. BABYLON.AudioEngine = AudioEngine;
  35393. })(BABYLON || (BABYLON = {}));
  35394. var BABYLON;
  35395. (function (BABYLON) {
  35396. var Sound = (function () {
  35397. /**
  35398. * Create a sound and attach it to a scene
  35399. * @param name Name of your sound
  35400. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  35401. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  35402. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  35403. */
  35404. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  35405. var _this = this;
  35406. this.autoplay = false;
  35407. this.loop = false;
  35408. this.useCustomAttenuation = false;
  35409. this.spatialSound = false;
  35410. this.refDistance = 1;
  35411. this.rolloffFactor = 1;
  35412. this.maxDistance = 100;
  35413. this.distanceModel = "linear";
  35414. this._panningModel = "equalpower";
  35415. this._playbackRate = 1;
  35416. this._streaming = false;
  35417. this._startTime = 0;
  35418. this._startOffset = 0;
  35419. this._position = BABYLON.Vector3.Zero();
  35420. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  35421. this._volume = 1;
  35422. this._isLoaded = false;
  35423. this._isReadyToPlay = false;
  35424. this.isPlaying = false;
  35425. this.isPaused = false;
  35426. this._isDirectional = false;
  35427. // Used if you'd like to create a directional sound.
  35428. // If not set, the sound will be omnidirectional
  35429. this._coneInnerAngle = 360;
  35430. this._coneOuterAngle = 360;
  35431. this._coneOuterGain = 0;
  35432. this._isOutputConnected = false;
  35433. this.name = name;
  35434. this._scene = scene;
  35435. this._readyToPlayCallback = readyToPlayCallback;
  35436. // Default custom attenuation function is a linear attenuation
  35437. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  35438. if (currentDistance < maxDistance) {
  35439. return currentVolume * (1 - currentDistance / maxDistance);
  35440. }
  35441. else {
  35442. return 0;
  35443. }
  35444. };
  35445. if (options) {
  35446. this.autoplay = options.autoplay || false;
  35447. this.loop = options.loop || false;
  35448. // if volume === 0, we need another way to check this option
  35449. if (options.volume !== undefined) {
  35450. this._volume = options.volume;
  35451. }
  35452. this.spatialSound = options.spatialSound || false;
  35453. this.maxDistance = options.maxDistance || 100;
  35454. this.useCustomAttenuation = options.useCustomAttenuation || false;
  35455. this.rolloffFactor = options.rolloffFactor || 1;
  35456. this.refDistance = options.refDistance || 1;
  35457. this.distanceModel = options.distanceModel || "linear";
  35458. this._playbackRate = options.playbackRate || 1;
  35459. this._streaming = options.streaming || false;
  35460. }
  35461. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35462. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  35463. this._soundGain.gain.value = this._volume;
  35464. this._inputAudioNode = this._soundGain;
  35465. this._ouputAudioNode = this._soundGain;
  35466. if (this.spatialSound) {
  35467. this._createSpatialParameters();
  35468. }
  35469. this._scene.mainSoundTrack.AddSound(this);
  35470. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  35471. if (urlOrArrayBuffer) {
  35472. // If it's an URL
  35473. if (typeof (urlOrArrayBuffer) === "string") {
  35474. // Loading sound using XHR2
  35475. if (!this._streaming) {
  35476. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  35477. }
  35478. else {
  35479. this._htmlAudioElement = new Audio(urlOrArrayBuffer);
  35480. this._htmlAudioElement.controls = false;
  35481. this._htmlAudioElement.loop = this.loop;
  35482. this._htmlAudioElement.crossOrigin = "anonymous";
  35483. this._htmlAudioElement.preload = "auto";
  35484. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  35485. _this._isReadyToPlay = true;
  35486. if (_this.autoplay) {
  35487. _this.play();
  35488. }
  35489. if (_this._readyToPlayCallback) {
  35490. _this._readyToPlayCallback();
  35491. }
  35492. });
  35493. document.body.appendChild(this._htmlAudioElement);
  35494. }
  35495. }
  35496. else {
  35497. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  35498. if (urlOrArrayBuffer.byteLength > 0) {
  35499. this._soundLoaded(urlOrArrayBuffer);
  35500. }
  35501. }
  35502. else {
  35503. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  35504. }
  35505. }
  35506. }
  35507. }
  35508. else {
  35509. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  35510. this._scene.mainSoundTrack.AddSound(this);
  35511. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  35512. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  35513. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  35514. }
  35515. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  35516. if (this._readyToPlayCallback) {
  35517. window.setTimeout(function () {
  35518. _this._readyToPlayCallback();
  35519. }, 1000);
  35520. }
  35521. }
  35522. }
  35523. Sound.prototype.dispose = function () {
  35524. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  35525. if (this.isPlaying) {
  35526. this.stop();
  35527. }
  35528. this._isReadyToPlay = false;
  35529. if (this.soundTrackId === -1) {
  35530. this._scene.mainSoundTrack.RemoveSound(this);
  35531. }
  35532. else {
  35533. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  35534. }
  35535. if (this._soundGain) {
  35536. this._soundGain.disconnect();
  35537. this._soundGain = null;
  35538. }
  35539. if (this._soundPanner) {
  35540. this._soundPanner.disconnect();
  35541. this._soundPanner = null;
  35542. }
  35543. if (this._soundSource) {
  35544. this._soundSource.disconnect();
  35545. this._soundSource = null;
  35546. }
  35547. this._audioBuffer = null;
  35548. if (this._htmlAudioElement) {
  35549. this._htmlAudioElement.pause();
  35550. this._htmlAudioElement.src = "";
  35551. document.body.removeChild(this._htmlAudioElement);
  35552. }
  35553. if (this._connectedMesh) {
  35554. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35555. this._connectedMesh = null;
  35556. }
  35557. }
  35558. };
  35559. Sound.prototype._soundLoaded = function (audioData) {
  35560. var _this = this;
  35561. this._isLoaded = true;
  35562. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  35563. _this._audioBuffer = buffer;
  35564. _this._isReadyToPlay = true;
  35565. if (_this.autoplay) {
  35566. _this.play();
  35567. }
  35568. if (_this._readyToPlayCallback) {
  35569. _this._readyToPlayCallback();
  35570. }
  35571. }, function () { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name); });
  35572. };
  35573. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  35574. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35575. this._audioBuffer = audioBuffer;
  35576. this._isReadyToPlay = true;
  35577. }
  35578. };
  35579. Sound.prototype.updateOptions = function (options) {
  35580. if (options) {
  35581. this.loop = options.loop || this.loop;
  35582. this.maxDistance = options.maxDistance || this.maxDistance;
  35583. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  35584. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  35585. this.refDistance = options.refDistance || this.refDistance;
  35586. this.distanceModel = options.distanceModel || this.distanceModel;
  35587. this._playbackRate = options.playbackRate || this._playbackRate;
  35588. this._updateSpatialParameters();
  35589. if (this.isPlaying) {
  35590. if (this._streaming) {
  35591. this._htmlAudioElement.playbackRate = this._playbackRate;
  35592. }
  35593. else {
  35594. this._soundSource.playbackRate.value = this._playbackRate;
  35595. }
  35596. }
  35597. }
  35598. };
  35599. Sound.prototype._createSpatialParameters = function () {
  35600. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35601. if (this._scene.headphone) {
  35602. this._panningModel = "HRTF";
  35603. }
  35604. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  35605. this._updateSpatialParameters();
  35606. this._soundPanner.connect(this._ouputAudioNode);
  35607. this._inputAudioNode = this._soundPanner;
  35608. }
  35609. };
  35610. Sound.prototype._updateSpatialParameters = function () {
  35611. if (this.spatialSound) {
  35612. if (this.useCustomAttenuation) {
  35613. // Tricks to disable in a way embedded Web Audio attenuation
  35614. this._soundPanner.distanceModel = "linear";
  35615. this._soundPanner.maxDistance = Number.MAX_VALUE;
  35616. this._soundPanner.refDistance = 1;
  35617. this._soundPanner.rolloffFactor = 1;
  35618. this._soundPanner.panningModel = this._panningModel;
  35619. }
  35620. else {
  35621. this._soundPanner.distanceModel = this.distanceModel;
  35622. this._soundPanner.maxDistance = this.maxDistance;
  35623. this._soundPanner.refDistance = this.refDistance;
  35624. this._soundPanner.rolloffFactor = this.rolloffFactor;
  35625. this._soundPanner.panningModel = this._panningModel;
  35626. }
  35627. }
  35628. };
  35629. Sound.prototype.switchPanningModelToHRTF = function () {
  35630. this._panningModel = "HRTF";
  35631. this._switchPanningModel();
  35632. };
  35633. Sound.prototype.switchPanningModelToEqualPower = function () {
  35634. this._panningModel = "equalpower";
  35635. this._switchPanningModel();
  35636. };
  35637. Sound.prototype._switchPanningModel = function () {
  35638. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35639. this._soundPanner.panningModel = this._panningModel;
  35640. }
  35641. };
  35642. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  35643. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35644. if (this._isOutputConnected) {
  35645. this._ouputAudioNode.disconnect();
  35646. }
  35647. this._ouputAudioNode.connect(soundTrackAudioNode);
  35648. this._isOutputConnected = true;
  35649. }
  35650. };
  35651. /**
  35652. * Transform this sound into a directional source
  35653. * @param coneInnerAngle Size of the inner cone in degree
  35654. * @param coneOuterAngle Size of the outer cone in degree
  35655. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  35656. */
  35657. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  35658. if (coneOuterAngle < coneInnerAngle) {
  35659. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  35660. return;
  35661. }
  35662. this._coneInnerAngle = coneInnerAngle;
  35663. this._coneOuterAngle = coneOuterAngle;
  35664. this._coneOuterGain = coneOuterGain;
  35665. this._isDirectional = true;
  35666. if (this.isPlaying && this.loop) {
  35667. this.stop();
  35668. this.play();
  35669. }
  35670. };
  35671. Sound.prototype.setPosition = function (newPosition) {
  35672. this._position = newPosition;
  35673. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  35674. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35675. }
  35676. };
  35677. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  35678. this._localDirection = newLocalDirection;
  35679. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  35680. this._updateDirection();
  35681. }
  35682. };
  35683. Sound.prototype._updateDirection = function () {
  35684. var mat = this._connectedMesh.getWorldMatrix();
  35685. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  35686. direction.normalize();
  35687. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  35688. };
  35689. Sound.prototype.updateDistanceFromListener = function () {
  35690. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  35691. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  35692. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  35693. }
  35694. };
  35695. Sound.prototype.setAttenuationFunction = function (callback) {
  35696. this._customAttenuationFunction = callback;
  35697. };
  35698. /**
  35699. * Play the sound
  35700. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  35701. * @param offset (optional) Start the sound setting it at a specific time
  35702. */
  35703. Sound.prototype.play = function (time, offset) {
  35704. var _this = this;
  35705. if (this._isReadyToPlay && this._scene.audioEnabled) {
  35706. try {
  35707. if (this._startOffset < 0) {
  35708. time = -this._startOffset;
  35709. this._startOffset = 0;
  35710. }
  35711. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35712. if (!this._soundSource || !this._streamingSource) {
  35713. if (this.spatialSound) {
  35714. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  35715. if (this._isDirectional) {
  35716. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  35717. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  35718. this._soundPanner.coneOuterGain = this._coneOuterGain;
  35719. if (this._connectedMesh) {
  35720. this._updateDirection();
  35721. }
  35722. else {
  35723. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  35724. }
  35725. }
  35726. }
  35727. }
  35728. if (this._streaming) {
  35729. if (!this._streamingSource) {
  35730. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  35731. this._htmlAudioElement.onended = function () { _this._onended(); };
  35732. this._htmlAudioElement.playbackRate = this._playbackRate;
  35733. }
  35734. this._streamingSource.disconnect();
  35735. this._streamingSource.connect(this._inputAudioNode);
  35736. this._htmlAudioElement.play();
  35737. }
  35738. else {
  35739. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  35740. this._soundSource.buffer = this._audioBuffer;
  35741. this._soundSource.connect(this._inputAudioNode);
  35742. this._soundSource.loop = this.loop;
  35743. this._soundSource.playbackRate.value = this._playbackRate;
  35744. this._soundSource.onended = function () { _this._onended(); };
  35745. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  35746. }
  35747. this._startTime = startTime;
  35748. this.isPlaying = true;
  35749. this.isPaused = false;
  35750. }
  35751. catch (ex) {
  35752. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  35753. }
  35754. }
  35755. };
  35756. Sound.prototype._onended = function () {
  35757. this.isPlaying = false;
  35758. if (this.onended) {
  35759. this.onended();
  35760. }
  35761. };
  35762. /**
  35763. * Stop the sound
  35764. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  35765. */
  35766. Sound.prototype.stop = function (time) {
  35767. if (this.isPlaying) {
  35768. if (this._streaming) {
  35769. this._htmlAudioElement.pause();
  35770. // Test needed for Firefox or it will generate an Invalid State Error
  35771. if (this._htmlAudioElement.currentTime > 0) {
  35772. this._htmlAudioElement.currentTime = 0;
  35773. }
  35774. }
  35775. else {
  35776. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  35777. this._soundSource.stop(stopTime);
  35778. this._soundSource.onended = null;
  35779. if (!this.isPaused) {
  35780. this._startOffset = 0;
  35781. }
  35782. }
  35783. this.isPlaying = false;
  35784. }
  35785. };
  35786. Sound.prototype.pause = function () {
  35787. if (this.isPlaying) {
  35788. this.isPaused = true;
  35789. if (this._streaming) {
  35790. this._htmlAudioElement.pause();
  35791. }
  35792. else {
  35793. this.stop(0);
  35794. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  35795. }
  35796. }
  35797. };
  35798. Sound.prototype.setVolume = function (newVolume, time) {
  35799. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  35800. if (time) {
  35801. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  35802. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  35803. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  35804. }
  35805. else {
  35806. this._soundGain.gain.value = newVolume;
  35807. }
  35808. }
  35809. this._volume = newVolume;
  35810. };
  35811. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  35812. this._playbackRate = newPlaybackRate;
  35813. if (this.isPlaying) {
  35814. if (this._streaming) {
  35815. this._htmlAudioElement.playbackRate = this._playbackRate;
  35816. }
  35817. else {
  35818. this._soundSource.playbackRate.value = this._playbackRate;
  35819. }
  35820. }
  35821. };
  35822. Sound.prototype.getVolume = function () {
  35823. return this._volume;
  35824. };
  35825. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  35826. var _this = this;
  35827. if (this._connectedMesh) {
  35828. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35829. this._registerFunc = null;
  35830. }
  35831. this._connectedMesh = meshToConnectTo;
  35832. if (!this.spatialSound) {
  35833. this.spatialSound = true;
  35834. this._createSpatialParameters();
  35835. if (this.isPlaying && this.loop) {
  35836. this.stop();
  35837. this.play();
  35838. }
  35839. }
  35840. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  35841. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  35842. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  35843. };
  35844. Sound.prototype.detachFromMesh = function () {
  35845. if (this._connectedMesh) {
  35846. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  35847. this._registerFunc = null;
  35848. this._connectedMesh = null;
  35849. }
  35850. };
  35851. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  35852. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  35853. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  35854. this._updateDirection();
  35855. }
  35856. };
  35857. Sound.prototype.clone = function () {
  35858. var _this = this;
  35859. if (!this._streaming) {
  35860. var setBufferAndRun = function () {
  35861. if (_this._isReadyToPlay) {
  35862. clonedSound._audioBuffer = _this.getAudioBuffer();
  35863. clonedSound._isReadyToPlay = true;
  35864. if (clonedSound.autoplay) {
  35865. clonedSound.play();
  35866. }
  35867. }
  35868. else {
  35869. window.setTimeout(setBufferAndRun, 300);
  35870. }
  35871. };
  35872. var currentOptions = {
  35873. autoplay: this.autoplay, loop: this.loop,
  35874. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  35875. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  35876. refDistance: this.refDistance, distanceModel: this.distanceModel
  35877. };
  35878. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  35879. if (this.useCustomAttenuation) {
  35880. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  35881. }
  35882. clonedSound.setPosition(this._position);
  35883. clonedSound.setPlaybackRate(this._playbackRate);
  35884. setBufferAndRun();
  35885. return clonedSound;
  35886. }
  35887. else {
  35888. return null;
  35889. }
  35890. };
  35891. Sound.prototype.getAudioBuffer = function () {
  35892. return this._audioBuffer;
  35893. };
  35894. Sound.prototype.serialize = function () {
  35895. var serializationObject = {
  35896. name: this.name,
  35897. url: this.name,
  35898. autoplay: this.autoplay,
  35899. loop: this.loop,
  35900. volume: this._volume,
  35901. spatialSound: this.spatialSound,
  35902. maxDistance: this.maxDistance,
  35903. rolloffFactor: this.rolloffFactor,
  35904. refDistance: this.refDistance,
  35905. distanceModel: this.distanceModel,
  35906. playbackRate: this._playbackRate,
  35907. panningModel: this._panningModel,
  35908. soundTrackId: this.soundTrackId
  35909. };
  35910. if (this.spatialSound) {
  35911. if (this._connectedMesh)
  35912. serializationObject.connectedMeshId = this._connectedMesh.id;
  35913. serializationObject.position = this._position.asArray();
  35914. serializationObject.refDistance = this.refDistance;
  35915. serializationObject.distanceModel = this.distanceModel;
  35916. serializationObject.isDirectional = this._isDirectional;
  35917. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  35918. serializationObject.coneInnerAngle = this._coneInnerAngle;
  35919. serializationObject.coneOuterAngle = this._coneOuterAngle;
  35920. serializationObject.coneOuterGain = this._coneOuterGain;
  35921. }
  35922. return serializationObject;
  35923. };
  35924. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  35925. var soundName = parsedSound.name;
  35926. var soundUrl;
  35927. if (parsedSound.url) {
  35928. soundUrl = rootUrl + parsedSound.url;
  35929. }
  35930. else {
  35931. soundUrl = rootUrl + soundName;
  35932. }
  35933. var options = {
  35934. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  35935. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  35936. rolloffFactor: parsedSound.rolloffFactor,
  35937. refDistance: parsedSound.refDistance,
  35938. distanceModel: parsedSound.distanceModel,
  35939. playbackRate: parsedSound.playbackRate
  35940. };
  35941. var newSound;
  35942. if (!sourceSound) {
  35943. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  35944. scene._addPendingData(newSound);
  35945. }
  35946. else {
  35947. var setBufferAndRun = function () {
  35948. if (sourceSound._isReadyToPlay) {
  35949. newSound._audioBuffer = sourceSound.getAudioBuffer();
  35950. newSound._isReadyToPlay = true;
  35951. if (newSound.autoplay) {
  35952. newSound.play();
  35953. }
  35954. }
  35955. else {
  35956. window.setTimeout(setBufferAndRun, 300);
  35957. }
  35958. };
  35959. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  35960. setBufferAndRun();
  35961. }
  35962. if (parsedSound.position) {
  35963. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  35964. newSound.setPosition(soundPosition);
  35965. }
  35966. if (parsedSound.isDirectional) {
  35967. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  35968. if (parsedSound.localDirectionToMesh) {
  35969. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  35970. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  35971. }
  35972. }
  35973. if (parsedSound.connectedMeshId) {
  35974. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  35975. if (connectedMesh) {
  35976. newSound.attachToMesh(connectedMesh);
  35977. }
  35978. }
  35979. return newSound;
  35980. };
  35981. return Sound;
  35982. }());
  35983. BABYLON.Sound = Sound;
  35984. })(BABYLON || (BABYLON = {}));
  35985. var BABYLON;
  35986. (function (BABYLON) {
  35987. var SoundTrack = (function () {
  35988. function SoundTrack(scene, options) {
  35989. this.id = -1;
  35990. this._isMainTrack = false;
  35991. this._isInitialized = false;
  35992. this._scene = scene;
  35993. this.soundCollection = new Array();
  35994. this._options = options;
  35995. if (!this._isMainTrack) {
  35996. this._scene.soundTracks.push(this);
  35997. this.id = this._scene.soundTracks.length - 1;
  35998. }
  35999. }
  36000. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  36001. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36002. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  36003. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  36004. if (this._options) {
  36005. if (this._options.volume) {
  36006. this._outputAudioNode.gain.value = this._options.volume;
  36007. }
  36008. if (this._options.mainTrack) {
  36009. this._isMainTrack = this._options.mainTrack;
  36010. }
  36011. }
  36012. this._isInitialized = true;
  36013. }
  36014. };
  36015. SoundTrack.prototype.dispose = function () {
  36016. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36017. if (this._connectedAnalyser) {
  36018. this._connectedAnalyser.stopDebugCanvas();
  36019. }
  36020. while (this.soundCollection.length) {
  36021. this.soundCollection[0].dispose();
  36022. }
  36023. if (this._outputAudioNode) {
  36024. this._outputAudioNode.disconnect();
  36025. }
  36026. this._outputAudioNode = null;
  36027. }
  36028. };
  36029. SoundTrack.prototype.AddSound = function (sound) {
  36030. if (!this._isInitialized) {
  36031. this._initializeSoundTrackAudioGraph();
  36032. }
  36033. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36034. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  36035. }
  36036. if (sound.soundTrackId) {
  36037. if (sound.soundTrackId === -1) {
  36038. this._scene.mainSoundTrack.RemoveSound(sound);
  36039. }
  36040. else {
  36041. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  36042. }
  36043. }
  36044. this.soundCollection.push(sound);
  36045. sound.soundTrackId = this.id;
  36046. };
  36047. SoundTrack.prototype.RemoveSound = function (sound) {
  36048. var index = this.soundCollection.indexOf(sound);
  36049. if (index !== -1) {
  36050. this.soundCollection.splice(index, 1);
  36051. }
  36052. };
  36053. SoundTrack.prototype.setVolume = function (newVolume) {
  36054. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36055. this._outputAudioNode.gain.value = newVolume;
  36056. }
  36057. };
  36058. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  36059. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36060. for (var i = 0; i < this.soundCollection.length; i++) {
  36061. this.soundCollection[i].switchPanningModelToHRTF();
  36062. }
  36063. }
  36064. };
  36065. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  36066. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36067. for (var i = 0; i < this.soundCollection.length; i++) {
  36068. this.soundCollection[i].switchPanningModelToEqualPower();
  36069. }
  36070. }
  36071. };
  36072. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  36073. if (this._connectedAnalyser) {
  36074. this._connectedAnalyser.stopDebugCanvas();
  36075. }
  36076. this._connectedAnalyser = analyser;
  36077. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36078. this._outputAudioNode.disconnect();
  36079. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  36080. }
  36081. };
  36082. return SoundTrack;
  36083. }());
  36084. BABYLON.SoundTrack = SoundTrack;
  36085. })(BABYLON || (BABYLON = {}));
  36086. var BABYLON;
  36087. (function (BABYLON) {
  36088. var DebugLayer = (function () {
  36089. function DebugLayer(scene) {
  36090. var _this = this;
  36091. this._transformationMatrix = BABYLON.Matrix.Identity();
  36092. this._enabled = false;
  36093. this._labelsEnabled = false;
  36094. this._displayStatistics = true;
  36095. this._displayTree = false;
  36096. this._displayLogs = false;
  36097. this._skeletonViewers = new Array();
  36098. this._identityMatrix = BABYLON.Matrix.Identity();
  36099. this.axisRatio = 0.02;
  36100. this.accentColor = "orange";
  36101. this._scene = scene;
  36102. this._syncPositions = function () {
  36103. var engine = _this._scene.getEngine();
  36104. var canvasRect = engine.getRenderingCanvasClientRect();
  36105. if (_this._showUI) {
  36106. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  36107. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  36108. _this._statsDiv.style.width = "400px";
  36109. _this._statsDiv.style.height = "auto";
  36110. _this._statsSubsetDiv.style.maxHeight = "240px";
  36111. _this._optionsDiv.style.left = "0px";
  36112. _this._optionsDiv.style.top = "10px";
  36113. _this._optionsDiv.style.width = "200px";
  36114. _this._optionsDiv.style.height = "auto";
  36115. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  36116. _this._logDiv.style.left = "0px";
  36117. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  36118. _this._logDiv.style.width = "600px";
  36119. _this._logDiv.style.height = "160px";
  36120. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  36121. _this._treeDiv.style.top = "10px";
  36122. _this._treeDiv.style.width = "300px";
  36123. _this._treeDiv.style.height = "auto";
  36124. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  36125. }
  36126. _this._globalDiv.style.left = canvasRect.left + "px";
  36127. _this._globalDiv.style.top = canvasRect.top + "px";
  36128. _this._drawingCanvas.style.left = "0px";
  36129. _this._drawingCanvas.style.top = "0px";
  36130. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  36131. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  36132. var devicePixelRatio = window.devicePixelRatio || 1;
  36133. var context = _this._drawingContext;
  36134. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  36135. context.mozBackingStorePixelRatio ||
  36136. context.msBackingStorePixelRatio ||
  36137. context.oBackingStorePixelRatio ||
  36138. context.backingStorePixelRatio || 1;
  36139. _this._ratio = devicePixelRatio / backingStoreRatio;
  36140. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  36141. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  36142. };
  36143. this._onCanvasClick = function (evt) {
  36144. _this._clickPosition = {
  36145. x: evt.clientX * _this._ratio,
  36146. y: evt.clientY * _this._ratio
  36147. };
  36148. };
  36149. this._syncUI = function () {
  36150. if (_this._showUI) {
  36151. if (_this._displayStatistics) {
  36152. _this._displayStats();
  36153. _this._statsDiv.style.display = "";
  36154. }
  36155. else {
  36156. _this._statsDiv.style.display = "none";
  36157. }
  36158. if (_this._displayLogs) {
  36159. _this._logDiv.style.display = "";
  36160. }
  36161. else {
  36162. _this._logDiv.style.display = "none";
  36163. }
  36164. if (_this._displayTree) {
  36165. _this._treeDiv.style.display = "";
  36166. if (_this._needToRefreshMeshesTree) {
  36167. _this._needToRefreshMeshesTree = false;
  36168. _this._refreshMeshesTreeContent();
  36169. }
  36170. }
  36171. else {
  36172. _this._treeDiv.style.display = "none";
  36173. }
  36174. }
  36175. };
  36176. this._syncData = function () {
  36177. if (_this._labelsEnabled || !_this._showUI) {
  36178. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  36179. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  36180. var engine = _this._scene.getEngine();
  36181. var viewport = _this._camera.viewport;
  36182. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  36183. // Meshes
  36184. var meshes = _this._camera.getActiveMeshes();
  36185. var index;
  36186. var projectedPosition;
  36187. for (index = 0; index < meshes.length; index++) {
  36188. var mesh = meshes.data[index];
  36189. var position = mesh.getBoundingInfo().boundingSphere.center;
  36190. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36191. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  36192. _this._renderAxis(projectedPosition, mesh, globalViewport);
  36193. }
  36194. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  36195. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  36196. }
  36197. }
  36198. // Cameras
  36199. var cameras = _this._scene.cameras;
  36200. for (index = 0; index < cameras.length; index++) {
  36201. var camera = cameras[index];
  36202. if (camera === _this._camera) {
  36203. continue;
  36204. }
  36205. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  36206. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  36207. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  36208. _this._camera.detachControl(engine.getRenderingCanvas());
  36209. _this._camera = camera;
  36210. _this._camera.attachControl(engine.getRenderingCanvas());
  36211. }, function () { return "purple"; });
  36212. }
  36213. }
  36214. // Lights
  36215. var lights = _this._scene.lights;
  36216. for (index = 0; index < lights.length; index++) {
  36217. var light = lights[index];
  36218. if (light.position) {
  36219. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  36220. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  36221. _this._renderLabel(light.name, projectedPosition, -20, function () {
  36222. light.setEnabled(!light.isEnabled());
  36223. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  36224. }
  36225. }
  36226. }
  36227. }
  36228. _this._clickPosition = undefined;
  36229. };
  36230. }
  36231. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  36232. while (this._treeSubsetDiv.hasChildNodes()) {
  36233. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  36234. }
  36235. // Add meshes
  36236. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  36237. sortedArray.sort(function (a, b) {
  36238. if (a.name === b.name) {
  36239. return 0;
  36240. }
  36241. return (a.name > b.name) ? 1 : -1;
  36242. });
  36243. for (var index = 0; index < sortedArray.length; index++) {
  36244. var mesh = sortedArray[index];
  36245. if (!mesh.isEnabled()) {
  36246. continue;
  36247. }
  36248. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  36249. m.isVisible = element.checked;
  36250. }, mesh);
  36251. }
  36252. };
  36253. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  36254. this._drawingContext.beginPath();
  36255. this._drawingContext.moveTo(zero.x, zero.y);
  36256. this._drawingContext.lineTo(unit.x, unit.y);
  36257. this._drawingContext.strokeStyle = color;
  36258. this._drawingContext.lineWidth = 4;
  36259. this._drawingContext.stroke();
  36260. this._drawingContext.font = "normal 14px Segoe UI";
  36261. this._drawingContext.fillStyle = color;
  36262. this._drawingContext.fillText(label, unitText.x, unitText.y);
  36263. };
  36264. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  36265. var position = mesh.getBoundingInfo().boundingSphere.center;
  36266. var worldMatrix = mesh.getWorldMatrix();
  36267. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  36268. var unit = (unprojectedVector.subtract(position)).length();
  36269. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36270. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36271. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  36272. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36273. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  36274. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  36275. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  36276. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  36277. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  36278. };
  36279. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  36280. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  36281. this._drawingContext.font = "normal 12px Segoe UI";
  36282. var textMetrics = this._drawingContext.measureText(text);
  36283. var centerX = projectedPosition.x - textMetrics.width / 2;
  36284. var centerY = projectedPosition.y;
  36285. var clientRect = this._drawingCanvas.getBoundingClientRect();
  36286. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  36287. onClick();
  36288. }
  36289. this._drawingContext.beginPath();
  36290. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  36291. this._drawingContext.fillStyle = getFillStyle();
  36292. this._drawingContext.globalAlpha = 0.5;
  36293. this._drawingContext.fill();
  36294. this._drawingContext.globalAlpha = 1.0;
  36295. this._drawingContext.strokeStyle = '#FFFFFF';
  36296. this._drawingContext.lineWidth = 1;
  36297. this._drawingContext.stroke();
  36298. this._drawingContext.fillStyle = "#FFFFFF";
  36299. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  36300. this._drawingContext.beginPath();
  36301. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  36302. this._drawingContext.fill();
  36303. }
  36304. };
  36305. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  36306. if (!this._clickPosition) {
  36307. return false;
  36308. }
  36309. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  36310. return false;
  36311. }
  36312. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  36313. return false;
  36314. }
  36315. return true;
  36316. };
  36317. DebugLayer.prototype.isVisible = function () {
  36318. return this._enabled;
  36319. };
  36320. DebugLayer.prototype.hide = function () {
  36321. if (!this._enabled) {
  36322. return;
  36323. }
  36324. this._enabled = false;
  36325. var engine = this._scene.getEngine();
  36326. this._scene.unregisterBeforeRender(this._syncData);
  36327. this._scene.unregisterAfterRender(this._syncUI);
  36328. this._rootElement.removeChild(this._globalDiv);
  36329. this._scene.forceShowBoundingBoxes = false;
  36330. this._scene.forceWireframe = false;
  36331. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  36332. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  36333. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  36334. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  36335. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  36336. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  36337. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  36338. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  36339. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  36340. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  36341. this._scene.shadowsEnabled = true;
  36342. this._scene.particlesEnabled = true;
  36343. this._scene.postProcessesEnabled = true;
  36344. this._scene.collisionsEnabled = true;
  36345. this._scene.lightsEnabled = true;
  36346. this._scene.texturesEnabled = true;
  36347. this._scene.lensFlaresEnabled = true;
  36348. this._scene.proceduralTexturesEnabled = true;
  36349. this._scene.renderTargetsEnabled = true;
  36350. this._scene.probesEnabled = true;
  36351. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  36352. this._clearSkeletonViewers();
  36353. };
  36354. DebugLayer.prototype._clearSkeletonViewers = function () {
  36355. for (var index = 0; index < this._skeletonViewers.length; index++) {
  36356. this._skeletonViewers[index].dispose();
  36357. }
  36358. this._skeletonViewers = [];
  36359. };
  36360. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  36361. if (showUI === void 0) { showUI = true; }
  36362. if (camera === void 0) { camera = null; }
  36363. if (rootElement === void 0) { rootElement = null; }
  36364. if (this._enabled) {
  36365. return;
  36366. }
  36367. this._enabled = true;
  36368. if (camera) {
  36369. this._camera = camera;
  36370. }
  36371. else {
  36372. this._camera = this._scene.activeCamera;
  36373. }
  36374. this._showUI = showUI;
  36375. var engine = this._scene.getEngine();
  36376. this._globalDiv = document.createElement("div");
  36377. this._rootElement = rootElement || document.body;
  36378. this._rootElement.appendChild(this._globalDiv);
  36379. this._generateDOMelements();
  36380. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  36381. this._syncPositions();
  36382. this._scene.registerBeforeRender(this._syncData);
  36383. this._scene.registerAfterRender(this._syncUI);
  36384. };
  36385. DebugLayer.prototype._clearLabels = function () {
  36386. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  36387. for (var index = 0; index < this._scene.meshes.length; index++) {
  36388. var mesh = this._scene.meshes[index];
  36389. mesh.renderOverlay = false;
  36390. }
  36391. };
  36392. DebugLayer.prototype._generateheader = function (root, text) {
  36393. var header = document.createElement("div");
  36394. header.innerHTML = text + "&nbsp;";
  36395. header.style.textAlign = "right";
  36396. header.style.width = "100%";
  36397. header.style.color = "white";
  36398. header.style.backgroundColor = "Black";
  36399. header.style.padding = "5px 5px 4px 0px";
  36400. header.style.marginLeft = "-5px";
  36401. header.style.fontWeight = "bold";
  36402. root.appendChild(header);
  36403. };
  36404. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  36405. var label = document.createElement("label");
  36406. label.style.display = "inline";
  36407. label.innerHTML = title;
  36408. label.style.color = color;
  36409. root.appendChild(label);
  36410. root.appendChild(document.createElement("br"));
  36411. };
  36412. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  36413. if (tag === void 0) { tag = null; }
  36414. var label = document.createElement("label");
  36415. label.style.display = "inline";
  36416. var boundingBoxesCheckbox = document.createElement("input");
  36417. boundingBoxesCheckbox.type = "checkbox";
  36418. boundingBoxesCheckbox.checked = initialState;
  36419. boundingBoxesCheckbox.style.display = "inline";
  36420. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  36421. boundingBoxesCheckbox.style.verticalAlign = "sub";
  36422. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  36423. task(evt.target, tag);
  36424. });
  36425. label.appendChild(boundingBoxesCheckbox);
  36426. var container = document.createElement("span");
  36427. var leftPart = document.createElement("span");
  36428. var rightPart = document.createElement("span");
  36429. rightPart.style.cssFloat = "right";
  36430. leftPart.innerHTML = leftTitle;
  36431. rightPart.innerHTML = rightTitle;
  36432. rightPart.style.fontSize = "12px";
  36433. rightPart.style.maxWidth = "200px";
  36434. container.appendChild(leftPart);
  36435. container.appendChild(rightPart);
  36436. label.appendChild(container);
  36437. root.appendChild(label);
  36438. root.appendChild(document.createElement("br"));
  36439. };
  36440. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  36441. if (tag === void 0) { tag = null; }
  36442. var label = document.createElement("label");
  36443. label.style.display = "inline";
  36444. var checkBox = document.createElement("input");
  36445. checkBox.type = "checkbox";
  36446. checkBox.checked = initialState;
  36447. checkBox.style.display = "inline";
  36448. checkBox.style.margin = "0px 5px 0px 0px";
  36449. checkBox.style.verticalAlign = "sub";
  36450. checkBox.addEventListener("change", function (evt) {
  36451. task(evt.target, tag);
  36452. });
  36453. label.appendChild(checkBox);
  36454. label.appendChild(document.createTextNode(title));
  36455. root.appendChild(label);
  36456. root.appendChild(document.createElement("br"));
  36457. };
  36458. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  36459. if (tag === void 0) { tag = null; }
  36460. var button = document.createElement("button");
  36461. button.innerHTML = title;
  36462. button.style.height = "24px";
  36463. button.style.width = "150px";
  36464. button.style.marginBottom = "5px";
  36465. button.style.color = "#444444";
  36466. button.style.border = "1px solid white";
  36467. button.className = "debugLayerButton";
  36468. button.addEventListener("click", function (evt) {
  36469. task(evt.target, tag);
  36470. });
  36471. root.appendChild(button);
  36472. root.appendChild(document.createElement("br"));
  36473. };
  36474. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  36475. if (tag === void 0) { tag = null; }
  36476. var label = document.createElement("label");
  36477. label.style.display = "inline";
  36478. var boundingBoxesRadio = document.createElement("input");
  36479. boundingBoxesRadio.type = "radio";
  36480. boundingBoxesRadio.name = name;
  36481. boundingBoxesRadio.checked = initialState;
  36482. boundingBoxesRadio.style.display = "inline";
  36483. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  36484. boundingBoxesRadio.style.verticalAlign = "sub";
  36485. boundingBoxesRadio.addEventListener("change", function (evt) {
  36486. task(evt.target, tag);
  36487. });
  36488. label.appendChild(boundingBoxesRadio);
  36489. label.appendChild(document.createTextNode(title));
  36490. root.appendChild(label);
  36491. root.appendChild(document.createElement("br"));
  36492. };
  36493. DebugLayer.prototype._generateDOMelements = function () {
  36494. var _this = this;
  36495. this._globalDiv.id = "DebugLayer";
  36496. this._globalDiv.style.position = "absolute";
  36497. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  36498. this._globalDiv.style.fontSize = "14px";
  36499. this._globalDiv.style.color = "white";
  36500. // Drawing canvas
  36501. this._drawingCanvas = document.createElement("canvas");
  36502. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  36503. this._drawingCanvas.style.position = "absolute";
  36504. this._drawingCanvas.style.pointerEvents = "none";
  36505. this._drawingCanvas.style.backgroundColor = "transparent";
  36506. this._drawingContext = this._drawingCanvas.getContext("2d");
  36507. this._globalDiv.appendChild(this._drawingCanvas);
  36508. if (this._showUI) {
  36509. var background = "rgba(128, 128, 128, 0.4)";
  36510. var border = "rgb(180, 180, 180) solid 1px";
  36511. // Stats
  36512. this._statsDiv = document.createElement("div");
  36513. this._statsDiv.id = "DebugLayerStats";
  36514. this._statsDiv.style.border = border;
  36515. this._statsDiv.style.position = "absolute";
  36516. this._statsDiv.style.background = background;
  36517. this._statsDiv.style.padding = "0px 0px 0px 5px";
  36518. this._generateheader(this._statsDiv, "STATISTICS");
  36519. this._statsSubsetDiv = document.createElement("div");
  36520. this._statsSubsetDiv.style.paddingTop = "5px";
  36521. this._statsSubsetDiv.style.paddingBottom = "5px";
  36522. this._statsSubsetDiv.style.overflowY = "auto";
  36523. this._statsDiv.appendChild(this._statsSubsetDiv);
  36524. // Tree
  36525. this._treeDiv = document.createElement("div");
  36526. this._treeDiv.id = "DebugLayerTree";
  36527. this._treeDiv.style.border = border;
  36528. this._treeDiv.style.position = "absolute";
  36529. this._treeDiv.style.background = background;
  36530. this._treeDiv.style.padding = "0px 0px 0px 5px";
  36531. this._treeDiv.style.display = "none";
  36532. this._generateheader(this._treeDiv, "MESHES TREE");
  36533. this._treeSubsetDiv = document.createElement("div");
  36534. this._treeSubsetDiv.style.paddingTop = "5px";
  36535. this._treeSubsetDiv.style.paddingRight = "5px";
  36536. this._treeSubsetDiv.style.overflowY = "auto";
  36537. this._treeSubsetDiv.style.maxHeight = "300px";
  36538. this._treeDiv.appendChild(this._treeSubsetDiv);
  36539. this._needToRefreshMeshesTree = true;
  36540. // Logs
  36541. this._logDiv = document.createElement("div");
  36542. this._logDiv.style.border = border;
  36543. this._logDiv.id = "DebugLayerLogs";
  36544. this._logDiv.style.position = "absolute";
  36545. this._logDiv.style.background = background;
  36546. this._logDiv.style.padding = "0px 0px 0px 5px";
  36547. this._logDiv.style.display = "none";
  36548. this._generateheader(this._logDiv, "LOGS");
  36549. this._logSubsetDiv = document.createElement("div");
  36550. this._logSubsetDiv.style.height = "127px";
  36551. this._logSubsetDiv.style.paddingTop = "5px";
  36552. this._logSubsetDiv.style.overflowY = "auto";
  36553. this._logSubsetDiv.style.fontSize = "12px";
  36554. this._logSubsetDiv.style.fontFamily = "consolas";
  36555. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  36556. this._logDiv.appendChild(this._logSubsetDiv);
  36557. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  36558. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  36559. };
  36560. // Options
  36561. this._optionsDiv = document.createElement("div");
  36562. this._optionsDiv.id = "DebugLayerOptions";
  36563. this._optionsDiv.style.border = border;
  36564. this._optionsDiv.style.position = "absolute";
  36565. this._optionsDiv.style.background = background;
  36566. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  36567. this._optionsDiv.style.overflowY = "auto";
  36568. this._generateheader(this._optionsDiv, "OPTIONS");
  36569. this._optionsSubsetDiv = document.createElement("div");
  36570. this._optionsSubsetDiv.style.paddingTop = "5px";
  36571. this._optionsSubsetDiv.style.paddingBottom = "5px";
  36572. this._optionsSubsetDiv.style.overflowY = "auto";
  36573. this._optionsSubsetDiv.style.maxHeight = "200px";
  36574. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  36575. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  36576. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  36577. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  36578. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  36579. _this._displayTree = element.checked;
  36580. _this._needToRefreshMeshesTree = true;
  36581. });
  36582. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36583. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  36584. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  36585. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  36586. _this._labelsEnabled = element.checked;
  36587. if (!_this._labelsEnabled) {
  36588. _this._clearLabels();
  36589. }
  36590. });
  36591. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  36592. if (element.checked) {
  36593. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  36594. }
  36595. else {
  36596. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  36597. }
  36598. });
  36599. ;
  36600. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36601. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  36602. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  36603. if (element.checked) {
  36604. _this._scene.forceWireframe = false;
  36605. _this._scene.forcePointsCloud = false;
  36606. }
  36607. });
  36608. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  36609. if (element.checked) {
  36610. _this._scene.forceWireframe = true;
  36611. _this._scene.forcePointsCloud = false;
  36612. }
  36613. });
  36614. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  36615. if (element.checked) {
  36616. _this._scene.forceWireframe = false;
  36617. _this._scene.forcePointsCloud = true;
  36618. }
  36619. });
  36620. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36621. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  36622. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  36623. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  36624. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  36625. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  36626. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  36627. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  36628. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  36629. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  36630. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  36631. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  36632. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  36633. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36634. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  36635. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  36636. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  36637. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  36638. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  36639. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  36640. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  36641. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  36642. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  36643. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  36644. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  36645. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  36646. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  36647. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  36648. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  36649. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  36650. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36651. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  36652. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  36653. if (element.checked) {
  36654. _this._scene.headphone = true;
  36655. }
  36656. });
  36657. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  36658. if (element.checked) {
  36659. _this._scene.headphone = false;
  36660. }
  36661. });
  36662. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  36663. _this._scene.audioEnabled = !element.checked;
  36664. });
  36665. }
  36666. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36667. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  36668. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  36669. if (!element.checked) {
  36670. _this._clearSkeletonViewers();
  36671. return;
  36672. }
  36673. for (var index = 0; index < _this._scene.meshes.length; index++) {
  36674. var mesh = _this._scene.meshes[index];
  36675. if (mesh.skeleton) {
  36676. var found = false;
  36677. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  36678. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  36679. found = true;
  36680. break;
  36681. }
  36682. }
  36683. if (found) {
  36684. continue;
  36685. }
  36686. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  36687. viewer.isEnabled = true;
  36688. _this._skeletonViewers.push(viewer);
  36689. }
  36690. }
  36691. });
  36692. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36693. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  36694. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  36695. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  36696. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  36697. if (_this._camera) {
  36698. console.log(_this._camera);
  36699. }
  36700. else {
  36701. console.warn("No camera defined, or debug layer created before camera creation!");
  36702. }
  36703. });
  36704. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  36705. this._globalDiv.appendChild(this._statsDiv);
  36706. this._globalDiv.appendChild(this._logDiv);
  36707. this._globalDiv.appendChild(this._optionsDiv);
  36708. this._globalDiv.appendChild(this._treeDiv);
  36709. }
  36710. };
  36711. DebugLayer.prototype._displayStats = function () {
  36712. var scene = this._scene;
  36713. var engine = scene.getEngine();
  36714. var glInfo = engine.getGlInfo();
  36715. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  36716. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36717. + "<b>Count</b><br>"
  36718. + "Total meshes: " + scene.meshes.length + "<br>"
  36719. + "Total lights: " + scene.lights.length + "<br>"
  36720. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  36721. + "Total materials: " + scene.materials.length + "<br>"
  36722. + "Total textures: " + scene.textures.length + "<br>"
  36723. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  36724. + "Active indices: " + scene.getActiveIndices() + "<br>"
  36725. + "Active bones: " + scene.getActiveBones() + "<br>"
  36726. + "Active particles: " + scene.getActiveParticles() + "<br>"
  36727. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  36728. + "<b>Duration</b><br>"
  36729. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  36730. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  36731. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  36732. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  36733. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  36734. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  36735. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  36736. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  36737. + "</div>"
  36738. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36739. + "<b>Extensions</b><br>"
  36740. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  36741. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  36742. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  36743. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  36744. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  36745. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  36746. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  36747. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  36748. + "</div><br>"
  36749. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  36750. + "<b>Caps.</b><br>"
  36751. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  36752. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  36753. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  36754. + "<b>Info</b><br>"
  36755. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  36756. + glInfo.version + "<br>"
  36757. + "</div><br>"
  36758. + glInfo.renderer + "<br>";
  36759. if (this.customStatsFunction) {
  36760. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  36761. }
  36762. };
  36763. return DebugLayer;
  36764. }());
  36765. BABYLON.DebugLayer = DebugLayer;
  36766. })(BABYLON || (BABYLON = {}));
  36767. var BABYLON;
  36768. (function (BABYLON) {
  36769. var SIMDVector3 = (function () {
  36770. function SIMDVector3() {
  36771. }
  36772. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  36773. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  36774. var m0 = SIMD.float32x4.load(transformation.m, 0);
  36775. var m1 = SIMD.float32x4.load(transformation.m, 4);
  36776. var m2 = SIMD.float32x4.load(transformation.m, 8);
  36777. var m3 = SIMD.float32x4.load(transformation.m, 12);
  36778. 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));
  36779. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  36780. SIMD.float32x4.storeXYZ(result._data, 0, r);
  36781. };
  36782. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  36783. var v0 = SIMD.float32x4.splat(x);
  36784. var v1 = SIMD.float32x4.splat(y);
  36785. var v2 = SIMD.float32x4.splat(z);
  36786. var m0 = SIMD.float32x4.load(transformation.m, 0);
  36787. var m1 = SIMD.float32x4.load(transformation.m, 4);
  36788. var m2 = SIMD.float32x4.load(transformation.m, 8);
  36789. var m3 = SIMD.float32x4.load(transformation.m, 12);
  36790. 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));
  36791. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  36792. SIMD.float32x4.storeXYZ(result._data, 0, r);
  36793. };
  36794. return SIMDVector3;
  36795. }());
  36796. BABYLON.SIMDVector3 = SIMDVector3;
  36797. var SIMDMatrix = (function () {
  36798. function SIMDMatrix() {
  36799. }
  36800. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  36801. if (offset === void 0) { offset = 0; }
  36802. var tm = this.m;
  36803. var om = other.m;
  36804. var om0 = SIMD.float32x4.load(om, 0);
  36805. var om1 = SIMD.float32x4.load(om, 4);
  36806. var om2 = SIMD.float32x4.load(om, 8);
  36807. var om3 = SIMD.float32x4.load(om, 12);
  36808. var tm0 = SIMD.float32x4.load(tm, 0);
  36809. 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)))));
  36810. var tm1 = SIMD.float32x4.load(tm, 4);
  36811. 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)))));
  36812. var tm2 = SIMD.float32x4.load(tm, 8);
  36813. 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)))));
  36814. var tm3 = SIMD.float32x4.load(tm, 12);
  36815. 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)))));
  36816. };
  36817. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  36818. var src = this.m;
  36819. var dest = other.m;
  36820. var row0, row1, row2, row3;
  36821. var tmp1;
  36822. var minor0, minor1, minor2, minor3;
  36823. var det;
  36824. // Load the 4 rows
  36825. var src0 = SIMD.float32x4.load(src, 0);
  36826. var src1 = SIMD.float32x4.load(src, 4);
  36827. var src2 = SIMD.float32x4.load(src, 8);
  36828. var src3 = SIMD.float32x4.load(src, 12);
  36829. // Transpose the source matrix. Sort of. Not a true transpose operation
  36830. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  36831. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  36832. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  36833. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  36834. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  36835. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  36836. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  36837. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  36838. // This is a true transposition, but it will lead to an incorrect result
  36839. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  36840. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  36841. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  36842. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  36843. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  36844. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  36845. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  36846. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  36847. // ----
  36848. tmp1 = SIMD.float32x4.mul(row2, row3);
  36849. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36850. minor0 = SIMD.float32x4.mul(row1, tmp1);
  36851. minor1 = SIMD.float32x4.mul(row0, tmp1);
  36852. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36853. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  36854. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  36855. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  36856. // ----
  36857. tmp1 = SIMD.float32x4.mul(row1, row2);
  36858. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36859. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  36860. minor3 = SIMD.float32x4.mul(row0, tmp1);
  36861. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36862. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  36863. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  36864. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  36865. // ----
  36866. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  36867. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36868. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  36869. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  36870. minor2 = SIMD.float32x4.mul(row0, tmp1);
  36871. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36872. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  36873. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  36874. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  36875. // ----
  36876. tmp1 = SIMD.float32x4.mul(row0, row1);
  36877. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36878. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  36879. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  36880. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36881. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  36882. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  36883. // ----
  36884. tmp1 = SIMD.float32x4.mul(row0, row3);
  36885. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36886. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  36887. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  36888. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36889. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  36890. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  36891. // ----
  36892. tmp1 = SIMD.float32x4.mul(row0, row2);
  36893. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  36894. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  36895. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  36896. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  36897. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  36898. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  36899. // Compute determinant
  36900. det = SIMD.float32x4.mul(row0, minor0);
  36901. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  36902. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  36903. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  36904. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  36905. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  36906. // These shuffles aren't necessary if the faulty transposition is done
  36907. // up at the top of this function.
  36908. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  36909. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  36910. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  36911. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  36912. // Compute final values by multiplying with 1/det
  36913. minor0 = SIMD.float32x4.mul(det, minor0);
  36914. minor1 = SIMD.float32x4.mul(det, minor1);
  36915. minor2 = SIMD.float32x4.mul(det, minor2);
  36916. minor3 = SIMD.float32x4.mul(det, minor3);
  36917. SIMD.float32x4.store(dest, 0, minor0);
  36918. SIMD.float32x4.store(dest, 4, minor1);
  36919. SIMD.float32x4.store(dest, 8, minor2);
  36920. SIMD.float32x4.store(dest, 12, minor3);
  36921. return this;
  36922. };
  36923. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  36924. var out = result.m;
  36925. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  36926. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  36927. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  36928. // cc.kmVec3Subtract(f, pCenter, pEye);
  36929. var f = SIMD.float32x4.sub(center, eye);
  36930. // cc.kmVec3Normalize(f, f);
  36931. var tmp = SIMD.float32x4.mul(f, f);
  36932. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36933. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36934. // cc.kmVec3Assign(up, pUp);
  36935. // cc.kmVec3Normalize(up, up);
  36936. tmp = SIMD.float32x4.mul(up, up);
  36937. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36938. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36939. // cc.kmVec3Cross(s, f, up);
  36940. 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)));
  36941. // cc.kmVec3Normalize(s, s);
  36942. tmp = SIMD.float32x4.mul(s, s);
  36943. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36944. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36945. // cc.kmVec3Cross(u, s, f);
  36946. 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)));
  36947. // cc.kmVec3Normalize(s, s);
  36948. tmp = SIMD.float32x4.mul(s, s);
  36949. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  36950. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  36951. var zero = SIMD.float32x4.splat(0.0);
  36952. s = SIMD.float32x4.neg(s);
  36953. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  36954. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  36955. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  36956. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  36957. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  36958. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  36959. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  36960. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  36961. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  36962. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  36963. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  36964. var b3 = SIMD.float32x4.neg(eye);
  36965. b3 = SIMD.float32x4.withW(b3, 1.0);
  36966. 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)))));
  36967. 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)))));
  36968. 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)))));
  36969. 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)))));
  36970. };
  36971. return SIMDMatrix;
  36972. }());
  36973. BABYLON.SIMDMatrix = SIMDMatrix;
  36974. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  36975. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  36976. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  36977. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  36978. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  36979. var SIMDHelper = (function () {
  36980. function SIMDHelper() {
  36981. }
  36982. Object.defineProperty(SIMDHelper, "IsEnabled", {
  36983. get: function () {
  36984. return SIMDHelper._isEnabled;
  36985. },
  36986. enumerable: true,
  36987. configurable: true
  36988. });
  36989. SIMDHelper.DisableSIMD = function () {
  36990. // Replace functions
  36991. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  36992. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  36993. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  36994. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  36995. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  36996. SIMDHelper._isEnabled = false;
  36997. };
  36998. SIMDHelper.EnableSIMD = function () {
  36999. if (window.SIMD === undefined) {
  37000. return;
  37001. }
  37002. // Replace functions
  37003. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  37004. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  37005. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  37006. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  37007. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  37008. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  37009. get: function () { return this._data[0]; },
  37010. set: function (value) {
  37011. if (!this._data) {
  37012. this._data = new Float32Array(3);
  37013. }
  37014. this._data[0] = value;
  37015. }
  37016. });
  37017. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  37018. get: function () { return this._data[1]; },
  37019. set: function (value) {
  37020. this._data[1] = value;
  37021. }
  37022. });
  37023. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  37024. get: function () { return this._data[2]; },
  37025. set: function (value) {
  37026. this._data[2] = value;
  37027. }
  37028. });
  37029. SIMDHelper._isEnabled = true;
  37030. };
  37031. SIMDHelper._isEnabled = false;
  37032. return SIMDHelper;
  37033. }());
  37034. BABYLON.SIMDHelper = SIMDHelper;
  37035. })(BABYLON || (BABYLON = {}));
  37036. var BABYLON;
  37037. (function (BABYLON) {
  37038. /**
  37039. * This class describe a rectangle that were added to the map.
  37040. * You have access to its coordinates either in pixel or normalized (UV)
  37041. */
  37042. var PackedRect = (function () {
  37043. function PackedRect(root, parent, pos, size) {
  37044. this._pos = pos;
  37045. this._size = size;
  37046. this._root = root;
  37047. this._parent = parent;
  37048. }
  37049. Object.defineProperty(PackedRect.prototype, "pos", {
  37050. /**
  37051. * @returns the position of this node into the map
  37052. */
  37053. get: function () {
  37054. return this._pos;
  37055. },
  37056. enumerable: true,
  37057. configurable: true
  37058. });
  37059. Object.defineProperty(PackedRect.prototype, "contentSize", {
  37060. /**
  37061. * @returns the size of the rectangle this node handles
  37062. */
  37063. get: function () {
  37064. return this._contentSize;
  37065. },
  37066. enumerable: true,
  37067. configurable: true
  37068. });
  37069. Object.defineProperty(PackedRect.prototype, "UVs", {
  37070. /**
  37071. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  37072. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  37073. */
  37074. get: function () {
  37075. return this.getUVsForCustomSize(this._root._size);
  37076. },
  37077. enumerable: true,
  37078. configurable: true
  37079. });
  37080. /**
  37081. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations) and then using only a part of the PackRect.
  37082. * This method will return the UVs for this part by given the custom size of what you really use
  37083. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  37084. */
  37085. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  37086. var mainWidth = this._root._size.width;
  37087. var mainHeight = this._root._size.height;
  37088. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  37089. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  37090. var uvs = new Array();
  37091. uvs.push(topLeft);
  37092. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  37093. uvs.push(rightBottom);
  37094. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  37095. return uvs;
  37096. };
  37097. /**
  37098. * Free this rectangle from the map.
  37099. * Call this method when you no longer need the rectangle to be in the map.
  37100. */
  37101. PackedRect.prototype.freeContent = function () {
  37102. if (!this.contentSize) {
  37103. return;
  37104. }
  37105. this._contentSize = null;
  37106. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  37107. this.attemptDefrag();
  37108. };
  37109. Object.defineProperty(PackedRect.prototype, "isUsed", {
  37110. get: function () {
  37111. return this._contentSize != null || this._leftNode != null;
  37112. },
  37113. enumerable: true,
  37114. configurable: true
  37115. });
  37116. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  37117. var node = this.findNode(contentSize);
  37118. // Not enough space...
  37119. if (!node) {
  37120. return null;
  37121. }
  37122. node.splitNode(contentSize);
  37123. return node;
  37124. };
  37125. PackedRect.prototype.findNode = function (size) {
  37126. var resNode = null;
  37127. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  37128. if (this.isUsed) {
  37129. if (this._leftNode) {
  37130. resNode = this._leftNode.findNode(size);
  37131. }
  37132. if (!resNode && this._rightNode) {
  37133. resNode = this._rightNode.findNode(size);
  37134. }
  37135. if (!resNode && this._bottomNode) {
  37136. resNode = this._bottomNode.findNode(size);
  37137. }
  37138. }
  37139. else if (this._initialSize && (size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  37140. resNode = this;
  37141. }
  37142. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  37143. resNode = this;
  37144. }
  37145. return resNode;
  37146. };
  37147. PackedRect.prototype.splitNode = function (contentSize) {
  37148. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  37149. if (!this._contentSize && this._initialSize) {
  37150. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  37151. return this._leftNode.splitNode(contentSize);
  37152. }
  37153. else {
  37154. this._contentSize = contentSize.clone();
  37155. this._initialSize = contentSize.clone();
  37156. if (contentSize.width !== this._size.width) {
  37157. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + contentSize.width, this._pos.y), new BABYLON.Size(this._size.width - contentSize.width, contentSize.height));
  37158. }
  37159. if (contentSize.height !== this._size.height) {
  37160. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + contentSize.height), new BABYLON.Size(this._size.width, this._size.height - contentSize.height));
  37161. }
  37162. return this;
  37163. }
  37164. };
  37165. PackedRect.prototype.attemptDefrag = function () {
  37166. if (!this.isUsed && this.isRecursiveFree) {
  37167. this.clearNode();
  37168. if (this._parent) {
  37169. this._parent.attemptDefrag();
  37170. }
  37171. }
  37172. };
  37173. PackedRect.prototype.clearNode = function () {
  37174. this._initialSize = null;
  37175. this._rightNode = null;
  37176. this._bottomNode = null;
  37177. };
  37178. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  37179. get: function () {
  37180. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  37181. },
  37182. enumerable: true,
  37183. configurable: true
  37184. });
  37185. PackedRect.prototype.evalFreeSize = function (size) {
  37186. var levelSize = 0;
  37187. if (!this.isUsed) {
  37188. if (this._initialSize) {
  37189. levelSize = this._initialSize.surface;
  37190. }
  37191. else {
  37192. levelSize = this._size.surface;
  37193. }
  37194. }
  37195. if (this._rightNode) {
  37196. levelSize += this._rightNode.evalFreeSize(0);
  37197. }
  37198. if (this._bottomNode) {
  37199. levelSize += this._bottomNode.evalFreeSize(0);
  37200. }
  37201. return levelSize + size;
  37202. };
  37203. return PackedRect;
  37204. }());
  37205. BABYLON.PackedRect = PackedRect;
  37206. /**
  37207. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  37208. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  37209. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
  37210. */
  37211. var RectPackingMap = (function (_super) {
  37212. __extends(RectPackingMap, _super);
  37213. /**
  37214. * Create an instance of the object with a dimension using the given size
  37215. * @param size The dimension of the rectangle that will contain all the sub ones.
  37216. */
  37217. function RectPackingMap(size) {
  37218. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  37219. this._root = this;
  37220. }
  37221. /**
  37222. * Add a rectangle, finding the best location to store it into the map
  37223. * @param size the dimension of the rectangle to store
  37224. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  37225. */
  37226. RectPackingMap.prototype.addRect = function (size) {
  37227. var node = this.findAndSplitNode(size);
  37228. return node;
  37229. };
  37230. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  37231. /**
  37232. * Return the current space free normalized between [0;1]
  37233. * @returns {}
  37234. */
  37235. get: function () {
  37236. var freeSize = 0;
  37237. freeSize = this.evalFreeSize(freeSize);
  37238. return freeSize / (this._size.width * this._size.height);
  37239. },
  37240. enumerable: true,
  37241. configurable: true
  37242. });
  37243. return RectPackingMap;
  37244. }(PackedRect));
  37245. BABYLON.RectPackingMap = RectPackingMap;
  37246. })(BABYLON || (BABYLON = {}));
  37247. var BABYLON;
  37248. (function (BABYLON) {
  37249. var DynamicFloatArrayElementInfo = (function () {
  37250. function DynamicFloatArrayElementInfo() {
  37251. }
  37252. return DynamicFloatArrayElementInfo;
  37253. }());
  37254. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  37255. /**
  37256. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  37257. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  37258. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  37259. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  37260. * Beware, calling pack() may change the offset of some Entries because this method will defragment the Float32Array to replace empty elements by moving allocated ones at their location.
  37261. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there are no "free holes".
  37262. */
  37263. var DynamicFloatArray = (function () {
  37264. /**
  37265. * Construct an instance of the dynamic float array
  37266. * @param stride size of one element in float (i.e. not bytes!)
  37267. * @param initialElementCount the number of available entries at construction
  37268. */
  37269. function DynamicFloatArray(stride, initialElementCount) {
  37270. this.compareValueOffset = null;
  37271. this.sortingAscending = true;
  37272. this._stride = stride;
  37273. this.buffer = new Float32Array(stride * initialElementCount);
  37274. this._lastUsed = 0;
  37275. this._firstFree = 0;
  37276. this._allEntries = new Array(initialElementCount);
  37277. this._freeEntries = new Array(initialElementCount);
  37278. for (var i = 0; i < initialElementCount; i++) {
  37279. var element = new DynamicFloatArrayElementInfo();
  37280. element.offset = i * stride;
  37281. this._allEntries[i] = element;
  37282. this._freeEntries[initialElementCount - i - 1] = element;
  37283. }
  37284. }
  37285. /**
  37286. * Allocate an element in the array.
  37287. * @return the element info instance that contains the offset into the main buffer of the element's location.
  37288. * Beware, this offset may change when you call pack()
  37289. */
  37290. DynamicFloatArray.prototype.allocElement = function () {
  37291. if (this._freeEntries.length === 0) {
  37292. this._growBuffer();
  37293. }
  37294. var el = this._freeEntries.pop();
  37295. this._lastUsed = Math.max(el.offset, this._lastUsed);
  37296. if (el.offset === this._firstFree) {
  37297. if (this._freeEntries.length > 0) {
  37298. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  37299. }
  37300. else {
  37301. this._firstFree += this._stride;
  37302. }
  37303. }
  37304. return el;
  37305. };
  37306. /**
  37307. * Free the element corresponding to the given element info
  37308. * @param elInfo the element that describe the allocated element
  37309. */
  37310. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  37311. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  37312. this._freeEntries.push(elInfo);
  37313. };
  37314. /**
  37315. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  37316. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  37317. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  37318. */
  37319. DynamicFloatArray.prototype.pack = function () {
  37320. // no free slot? no need to pack
  37321. if (this._freeEntries.length === 0) {
  37322. return this.buffer;
  37323. }
  37324. // If the buffer is already packed the last used will always be lower than the first free
  37325. // The opposite may not be true, we can have a lastUsed greater than firstFree but the array still packed, because when an element is freed, lastUsed is not updated (for speed reason) so we may have a lastUsed of a freed element. But that's ok, well soon realize this case.
  37326. if (this._lastUsed < this._firstFree) {
  37327. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  37328. return elementsBuffer_1;
  37329. }
  37330. var s = this._stride;
  37331. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  37332. var lastFree = new DynamicFloatArrayElementInfo();
  37333. lastFree.offset = this.totalElementCount * s;
  37334. this._freeEntries.push(lastFree);
  37335. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  37336. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37337. var firstFreeSlotOffset = sortedFree[0].offset;
  37338. var freeZoneSize = 1;
  37339. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  37340. var prevOffset = sortedFree[0].offset;
  37341. for (var i = 1; i < sortedFree.length; i++) {
  37342. // If the first free (which means everything before is occupied) is greater or equal the occupied zone size, it means everything is defragmented, we can quit
  37343. if (firstFreeSlotOffset >= occupiedZoneSize) {
  37344. break;
  37345. }
  37346. var curFree = sortedFree[i];
  37347. var curOffset = curFree.offset;
  37348. // Compute the distance between this offset and the previous
  37349. var distance = curOffset - prevOffset;
  37350. // If the distance is the stride size, they are adjacent, it good, move to the next
  37351. if (distance === s) {
  37352. // Free zone is one element bigger
  37353. ++freeZoneSize;
  37354. // as we're about to iterate to the next, the cur becomes the previous...
  37355. prevOffset = curOffset;
  37356. continue;
  37357. }
  37358. // Distance is bigger, which means there's x element between the previous free and this one
  37359. var usedRange = (distance / s) - 1;
  37360. // Two cases the free zone is smaller than the data to move or bigger
  37361. // Copy what can fit in the free zone
  37362. var curMoveOffset = curOffset - s;
  37363. var copyCount = Math.min(freeZoneSize, usedRange);
  37364. for (var j = 0; j < copyCount; j++) {
  37365. var freeI = firstFreeSlotOffset / s;
  37366. var curI = curMoveOffset / s;
  37367. var moveEl = sortedAll[curI];
  37368. this._moveElement(moveEl, firstFreeSlotOffset);
  37369. var replacedEl = sortedAll[freeI];
  37370. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  37371. replacedEl.offset = curMoveOffset;
  37372. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  37373. sortedAll[freeI] = moveEl;
  37374. sortedAll[curI] = replacedEl;
  37375. curMoveOffset -= s;
  37376. firstFreeSlotOffset += s;
  37377. }
  37378. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  37379. if (freeZoneSize <= usedRange) {
  37380. firstFreeSlotOffset = curMoveOffset + s;
  37381. freeZoneSize = 1 + copyCount;
  37382. }
  37383. else {
  37384. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  37385. }
  37386. // as we're about to iterate to the next, the cur becomes the previous...
  37387. prevOffset = curOffset;
  37388. }
  37389. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  37390. this._lastUsed = firstFreeSlotOffset - s;
  37391. this._firstFree = firstFreeSlotOffset;
  37392. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  37393. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  37394. this._allEntries = sortedAll;
  37395. return elementsBuffer;
  37396. };
  37397. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  37398. for (var i = 0; i < this._stride; i++) {
  37399. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  37400. }
  37401. element.offset = destOffset;
  37402. };
  37403. DynamicFloatArray.prototype._growBuffer = function () {
  37404. // Allocate the new buffer with 50% more entries, copy the content of the current one
  37405. var newElCount = Math.floor(this.totalElementCount * 1.5);
  37406. var newBuffer = new Float32Array(newElCount * this._stride);
  37407. newBuffer.set(this.buffer);
  37408. var curCount = this.totalElementCount;
  37409. var addedCount = newElCount - this.totalElementCount;
  37410. for (var i = 0; i < addedCount; i++) {
  37411. var element = new DynamicFloatArrayElementInfo();
  37412. element.offset = (curCount + i) * this.stride;
  37413. this._allEntries.push(element);
  37414. this._freeEntries[addedCount - i - 1] = element;
  37415. }
  37416. this._firstFree = curCount * this.stride;
  37417. this.buffer = newBuffer;
  37418. };
  37419. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  37420. /**
  37421. * Get the total count of entries that can fit in the current buffer
  37422. * @returns the elements count
  37423. */
  37424. get: function () {
  37425. return this._allEntries.length;
  37426. },
  37427. enumerable: true,
  37428. configurable: true
  37429. });
  37430. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  37431. /**
  37432. * Get the count of free entries that can still be allocated without resizing the buffer
  37433. * @returns the free elements count
  37434. */
  37435. get: function () {
  37436. return this._freeEntries.length;
  37437. },
  37438. enumerable: true,
  37439. configurable: true
  37440. });
  37441. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  37442. /**
  37443. * Get the count of allocated elements
  37444. * @returns the allocated elements count
  37445. */
  37446. get: function () {
  37447. return this._allEntries.length - this._freeEntries.length;
  37448. },
  37449. enumerable: true,
  37450. configurable: true
  37451. });
  37452. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  37453. /**
  37454. * Return the size of one element in float
  37455. * @returns the size in float
  37456. */
  37457. get: function () {
  37458. return this._stride;
  37459. },
  37460. enumerable: true,
  37461. configurable: true
  37462. });
  37463. DynamicFloatArray.prototype.sort = function () {
  37464. var _this = this;
  37465. if (!this.compareValueOffset) {
  37466. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  37467. }
  37468. var count = this.usedElementCount;
  37469. // Do we have to (re)create the sort table?
  37470. if (!this._sortTable || this._sortTable.length < count) {
  37471. // Small heuristic... We don't want to allocate totalElementCount right away because it may have 50 for 3 used elements, but on the other side we don't want to allocate just 3 when we just need 2, so double this value to give us some air to breath...
  37472. var newCount = Math.min(this.totalElementCount, count * 2);
  37473. this._sortTable = new Array(newCount);
  37474. }
  37475. if (!this._sortedTable || this._sortedTable.length !== count) {
  37476. this._sortedTable = new Array(count);
  37477. }
  37478. // Because, you know...
  37479. this.pack();
  37480. //let stride = this.stride;
  37481. //for (let i = 0; i < count; i++) {
  37482. // let si = this._sortTable[i];
  37483. // if (!si) {
  37484. // si = new SortInfo();
  37485. // this._sortTable[i] = si;
  37486. // }
  37487. // si.entry = this._allEntries[i];
  37488. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  37489. // si.swapedOffset = null;
  37490. // this._sortedTable[i] = si;
  37491. //}
  37492. var curOffset = 0;
  37493. var stride = this.stride;
  37494. for (var i = 0; i < count; i++, curOffset += stride) {
  37495. var si = this._sortTable[i];
  37496. if (!si) {
  37497. si = new SortInfo();
  37498. this._sortTable[i] = si;
  37499. }
  37500. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  37501. si.offset = curOffset;
  37502. si.swapedOffset = null;
  37503. this._sortedTable[i] = si;
  37504. }
  37505. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  37506. if (this.sortingAscending) {
  37507. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  37508. }
  37509. else {
  37510. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  37511. }
  37512. var swapElements = function (src, dst) {
  37513. for (var i = 0; i < stride; i++) {
  37514. var tps = _this.buffer[dst + i];
  37515. _this.buffer[dst + i] = _this.buffer[src + i];
  37516. _this.buffer[src + i] = tps;
  37517. }
  37518. };
  37519. // The fun part begin, sortedTable give us the ordered layout to obtain, to get that we have to move elements, but when we move an element:
  37520. // it replaces an existing one.I don't want to allocate a new Float32Array and do a raw copy, because it's awful (GC - wise),
  37521. // and I still want something with a good algorithm complexity.
  37522. // So here's the deal: we are going to swap elements, but we have to track the change of location of the element being replaced,
  37523. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  37524. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  37525. // When we'll look for and element, we'll check if its swapedOffset is set, if so we reiterate the operation with the one there
  37526. // until we find a SortInfo object without a swapedOffset which means we got the right location
  37527. // Yes, we may have to do multiple iterations to find the right location, but hey, it won't be huge: <3 in most cases, and it's better
  37528. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  37529. for (var i = 0; i < count; i++) {
  37530. // Get the element to move
  37531. var sourceSI = this._sortedTable[i];
  37532. var destSI = this._sortTable[i];
  37533. var sourceOff = sourceSI.offset;
  37534. // If the source changed location, find the new one
  37535. if (sourceSI.swapedOffset) {
  37536. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  37537. var curSI = sourceSI;
  37538. while (curSI.swapedOffset) {
  37539. curSI = this._sortTable[curSI.swapedOffset / stride];
  37540. }
  37541. // Finally get the right location
  37542. sourceOff = curSI.offset;
  37543. }
  37544. // Tag the element being replaced with its new location
  37545. destSI.swapedOffset = sourceOff;
  37546. // Swap elements (only if needed)
  37547. if (sourceOff !== destSI.offset) {
  37548. swapElements(sourceOff, destSI.offset);
  37549. }
  37550. // Update the offset in the corresponding DFAE
  37551. //sourceSI.entry.offset = destSI.entry.offset;
  37552. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  37553. }
  37554. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  37555. return true;
  37556. };
  37557. return DynamicFloatArray;
  37558. }());
  37559. BABYLON.DynamicFloatArray = DynamicFloatArray;
  37560. var SortInfo = (function () {
  37561. function SortInfo() {
  37562. this.compareData = this.offset = this.swapedOffset = null;
  37563. }
  37564. return SortInfo;
  37565. }());
  37566. })(BABYLON || (BABYLON = {}));
  37567. var BABYLON;
  37568. (function (BABYLON) {
  37569. /**
  37570. * This class given information about a given character.
  37571. */
  37572. var CharInfo = (function () {
  37573. function CharInfo() {
  37574. }
  37575. return CharInfo;
  37576. }());
  37577. BABYLON.CharInfo = CharInfo;
  37578. var FontTexture = (function (_super) {
  37579. __extends(FontTexture, _super);
  37580. /**
  37581. * Create a new instance of the FontTexture class
  37582. * @param name the name of the texture
  37583. * @param font the font to use, use the W3C CSS notation
  37584. * @param scene the scene that owns the texture
  37585. * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
  37586. * @param samplingMode the texture sampling mode
  37587. * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
  37588. */
  37589. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample) {
  37590. if (maxCharCount === void 0) { maxCharCount = 200; }
  37591. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37592. if (superSample === void 0) { superSample = false; }
  37593. _super.call(this, null, scene, true, false, samplingMode);
  37594. this._charInfos = {};
  37595. this._curCharCount = 0;
  37596. this._lastUpdateCharCount = -1;
  37597. this._usedCounter = 1;
  37598. this.name = name;
  37599. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37600. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37601. this._superSample = false;
  37602. if (superSample) {
  37603. var sfont = this.getSuperSampleFont(font);
  37604. if (sfont) {
  37605. this._superSample = true;
  37606. font = sfont;
  37607. }
  37608. }
  37609. // First canvas creation to determine the size of the texture to create
  37610. this._canvas = document.createElement("canvas");
  37611. this._context = this._canvas.getContext("2d");
  37612. this._context.font = font;
  37613. this._context.fillStyle = "white";
  37614. this._cachedFontId = null;
  37615. var res = this.getFontHeight(font);
  37616. this._lineHeightSuper = res.height;
  37617. this._lineHeight = this._superSample ? (this._lineHeightSuper / 2) : this._lineHeightSuper;
  37618. this._offset = res.offset - 1;
  37619. var maxCharWidth = this._context.measureText("W").width;
  37620. this._spaceWidthSuper = this._context.measureText(" ").width;
  37621. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  37622. // This is an approximate size, but should always be able to fit at least the maxCharCount
  37623. var totalEstSurface = this._lineHeightSuper * maxCharWidth * maxCharCount;
  37624. var edge = Math.sqrt(totalEstSurface);
  37625. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  37626. // Create the texture that will store the font characters
  37627. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  37628. var textureSize = this.getSize();
  37629. this.hasAlpha = true;
  37630. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  37631. this._canvas = document.createElement("canvas");
  37632. this._canvas.width = textureSize.width;
  37633. this._canvas.height = textureSize.height;
  37634. this._context = this._canvas.getContext("2d");
  37635. this._context.textBaseline = "top";
  37636. this._context.font = font;
  37637. this._context.fillStyle = "white";
  37638. this._context.imageSmoothingEnabled = false;
  37639. this._currentFreePosition = BABYLON.Vector2.Zero();
  37640. // Add the basic ASCII based characters
  37641. for (var i = 0x20; i < 0x7F; i++) {
  37642. var c = String.fromCharCode(i);
  37643. this.getChar(c);
  37644. }
  37645. this.update();
  37646. }
  37647. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  37648. get: function () {
  37649. return this._superSample;
  37650. },
  37651. enumerable: true,
  37652. configurable: true
  37653. });
  37654. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  37655. get: function () {
  37656. return this._spaceWidth;
  37657. },
  37658. enumerable: true,
  37659. configurable: true
  37660. });
  37661. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  37662. get: function () {
  37663. return this._lineHeight;
  37664. },
  37665. enumerable: true,
  37666. configurable: true
  37667. });
  37668. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample) {
  37669. if (supersample === void 0) { supersample = false; }
  37670. var s = scene;
  37671. if (!s.__fontTextureCache__) {
  37672. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  37673. }
  37674. var dic = s.__fontTextureCache__;
  37675. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  37676. var ft = dic.get(lfn);
  37677. if (ft) {
  37678. ++ft._usedCounter;
  37679. return ft;
  37680. }
  37681. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample);
  37682. ft._cachedFontId = lfn;
  37683. dic.add(lfn, ft);
  37684. return ft;
  37685. };
  37686. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample) {
  37687. if (supersample === void 0) { supersample = false; }
  37688. var s = scene;
  37689. var dic = s.__fontTextureCache__;
  37690. if (!dic) {
  37691. return;
  37692. }
  37693. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS");
  37694. var font = dic.get(lfn);
  37695. if (--font._usedCounter === 0) {
  37696. dic.remove(lfn);
  37697. font.dispose();
  37698. }
  37699. };
  37700. /**
  37701. * Make sure the given char is present in the font map.
  37702. * @param char the character to get or add
  37703. * @return the CharInfo instance corresponding to the given character
  37704. */
  37705. FontTexture.prototype.getChar = function (char) {
  37706. if (char.length !== 1) {
  37707. return null;
  37708. }
  37709. var info = this._charInfos[char];
  37710. if (info) {
  37711. return info;
  37712. }
  37713. info = new CharInfo();
  37714. var measure = this._context.measureText(char);
  37715. var textureSize = this.getSize();
  37716. // we reached the end of the current line?
  37717. var width = Math.round(measure.width);
  37718. var xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  37719. var yMargin = xMargin;
  37720. if (this._currentFreePosition.x + width + xMargin > textureSize.width) {
  37721. this._currentFreePosition.x = 0;
  37722. this._currentFreePosition.y += this._lineHeightSuper + yMargin;
  37723. // No more room?
  37724. if (this._currentFreePosition.y > textureSize.height) {
  37725. return this.getChar("!");
  37726. }
  37727. }
  37728. // Draw the character in the texture
  37729. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  37730. // Fill the CharInfo object
  37731. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  37732. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  37733. info.charWidth = this._superSample ? (width / 2) : width;
  37734. // Add the info structure
  37735. this._charInfos[char] = info;
  37736. this._curCharCount++;
  37737. // Set the next position
  37738. this._currentFreePosition.x += width + xMargin;
  37739. return info;
  37740. };
  37741. FontTexture.prototype.measureText = function (text, tabulationSize) {
  37742. if (tabulationSize === void 0) { tabulationSize = 4; }
  37743. var maxWidth = 0;
  37744. var curWidth = 0;
  37745. var lineCount = 1;
  37746. var charxpos = 0;
  37747. // Parse each char of the string
  37748. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  37749. var char = text_1[_i];
  37750. // Next line feed?
  37751. if (char === "\n") {
  37752. maxWidth = Math.max(maxWidth, curWidth);
  37753. charxpos = 0;
  37754. curWidth = 0;
  37755. ++lineCount;
  37756. continue;
  37757. }
  37758. // Tabulation ?
  37759. if (char === "\t") {
  37760. var nextPos = charxpos + tabulationSize;
  37761. nextPos = nextPos - (nextPos % tabulationSize);
  37762. curWidth += (nextPos - charxpos) * this.spaceWidth;
  37763. charxpos = nextPos;
  37764. continue;
  37765. }
  37766. if (char < " ") {
  37767. continue;
  37768. }
  37769. curWidth += this.getChar(char).charWidth;
  37770. ++charxpos;
  37771. }
  37772. maxWidth = Math.max(maxWidth, curWidth);
  37773. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  37774. };
  37775. FontTexture.prototype.getSuperSampleFont = function (font) {
  37776. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  37777. var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
  37778. var res = font.toLocaleLowerCase().match(regex);
  37779. if (res == null) {
  37780. return null;
  37781. }
  37782. var size = parseInt(res[4]);
  37783. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  37784. var newFont = "";
  37785. for (var j = 1; j < res.length; j++) {
  37786. if (res[j] != null) {
  37787. newFont += res[j] + " ";
  37788. }
  37789. }
  37790. return newFont;
  37791. };
  37792. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  37793. FontTexture.prototype.getFontHeight = function (font) {
  37794. var fontDraw = document.createElement("canvas");
  37795. var ctx = fontDraw.getContext('2d');
  37796. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  37797. ctx.textBaseline = 'top';
  37798. ctx.fillStyle = 'white';
  37799. ctx.font = font;
  37800. ctx.fillText('jH|', 0, 0);
  37801. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  37802. var start = -1;
  37803. var end = -1;
  37804. for (var row = 0; row < fontDraw.height; row++) {
  37805. for (var column = 0; column < fontDraw.width; column++) {
  37806. var index = (row * fontDraw.width + column) * 4;
  37807. if (pixels[index] === 0) {
  37808. if (column === fontDraw.width - 1 && start !== -1) {
  37809. end = row;
  37810. row = fontDraw.height;
  37811. break;
  37812. }
  37813. continue;
  37814. }
  37815. else {
  37816. if (start === -1) {
  37817. start = row;
  37818. }
  37819. break;
  37820. }
  37821. }
  37822. }
  37823. return { height: (end - start) + 1, offset: start - 1 };
  37824. };
  37825. Object.defineProperty(FontTexture.prototype, "canRescale", {
  37826. get: function () {
  37827. return false;
  37828. },
  37829. enumerable: true,
  37830. configurable: true
  37831. });
  37832. FontTexture.prototype.getContext = function () {
  37833. return this._context;
  37834. };
  37835. /**
  37836. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  37837. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  37838. */
  37839. FontTexture.prototype.update = function () {
  37840. // Update only if there's new char added since the previous update
  37841. if (this._lastUpdateCharCount < this._curCharCount) {
  37842. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  37843. this._lastUpdateCharCount = this._curCharCount;
  37844. }
  37845. };
  37846. // cloning should be prohibited, there's no point to duplicate this texture at all
  37847. FontTexture.prototype.clone = function () {
  37848. return null;
  37849. };
  37850. /**
  37851. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  37852. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  37853. */
  37854. FontTexture.prototype.incCachedFontTextureCounter = function () {
  37855. ++this._usedCounter;
  37856. };
  37857. /**
  37858. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  37859. */
  37860. FontTexture.prototype.decCachedFontTextureCounter = function () {
  37861. var s = this.getScene();
  37862. var dic = s.__fontTextureCache__;
  37863. if (!dic) {
  37864. return;
  37865. }
  37866. if (--this._usedCounter === 0) {
  37867. dic.remove(this._cachedFontId);
  37868. this.dispose();
  37869. }
  37870. };
  37871. return FontTexture;
  37872. }(BABYLON.Texture));
  37873. BABYLON.FontTexture = FontTexture;
  37874. })(BABYLON || (BABYLON = {}));
  37875. var BABYLON;
  37876. (function (BABYLON) {
  37877. var MapTexture = (function (_super) {
  37878. __extends(MapTexture, _super);
  37879. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  37880. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  37881. if (useMipMap === void 0) { useMipMap = false; }
  37882. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  37883. this.name = name;
  37884. this._size = size;
  37885. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37886. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37887. // Create the rectPackMap that will allocate portion of the texture
  37888. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  37889. // Create the texture that will store the content
  37890. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  37891. }
  37892. /**
  37893. * Allocate a rectangle of a given size in the texture map
  37894. * @param size the size of the rectangle to allocation
  37895. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  37896. */
  37897. MapTexture.prototype.allocateRect = function (size) {
  37898. return this._rectPackingMap.addRect(size);
  37899. };
  37900. /**
  37901. * Free a given rectangle from the texture map
  37902. * @param rectInfo the instance corresponding to the rect to free.
  37903. */
  37904. MapTexture.prototype.freeRect = function (rectInfo) {
  37905. if (rectInfo) {
  37906. rectInfo.freeContent();
  37907. }
  37908. };
  37909. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  37910. /**
  37911. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  37912. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  37913. * @returns {}
  37914. */
  37915. get: function () {
  37916. return this._rectPackingMap.freeSpace;
  37917. },
  37918. enumerable: true,
  37919. configurable: true
  37920. });
  37921. /**
  37922. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  37923. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  37924. * Don't forget to call unbindTexture when you're done rendering
  37925. * @param rect the zone to render to
  37926. * @param clear true to clear the portion's color/depth data
  37927. */
  37928. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  37929. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  37930. };
  37931. /**
  37932. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  37933. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  37934. * Don't forget to call unbindTexture when you're done rendering
  37935. * @param pos the position into the texture
  37936. * @param size the portion to fit the clip space to
  37937. * @param clear true to clear the portion's color/depth data
  37938. */
  37939. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  37940. var engine = this.getScene().getEngine();
  37941. engine.bindFramebuffer(this._texture);
  37942. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  37943. if (clear) {
  37944. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  37945. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  37946. }
  37947. };
  37948. /**
  37949. * Unbind the texture map from the rendering engine.
  37950. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  37951. * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
  37952. */
  37953. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  37954. // Dump ?
  37955. if (dumpForDebug) {
  37956. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  37957. }
  37958. var engine = this.getScene().getEngine();
  37959. if (this._replacedViewport) {
  37960. engine.setViewport(this._replacedViewport);
  37961. this._replacedViewport = null;
  37962. }
  37963. engine.unBindFramebuffer(this._texture);
  37964. };
  37965. Object.defineProperty(MapTexture.prototype, "canRescale", {
  37966. get: function () {
  37967. return false;
  37968. },
  37969. enumerable: true,
  37970. configurable: true
  37971. });
  37972. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  37973. // Anyway, there's not much point to use this method for this kind of texture I guess
  37974. MapTexture.prototype.clone = function () {
  37975. return null;
  37976. };
  37977. return MapTexture;
  37978. }(BABYLON.Texture));
  37979. BABYLON.MapTexture = MapTexture;
  37980. })(BABYLON || (BABYLON = {}));
  37981. var BABYLON;
  37982. (function (BABYLON) {
  37983. /**
  37984. * Stores 2D Bounding Information.
  37985. * This class handles a circle area and a bounding rectangle one.
  37986. */
  37987. var BoundingInfo2D = (function () {
  37988. function BoundingInfo2D() {
  37989. this.radius = 0;
  37990. this.center = BABYLON.Vector2.Zero();
  37991. this.extent = BABYLON.Vector2.Zero();
  37992. }
  37993. /**
  37994. * Create a BoundingInfo2D object from a given size
  37995. * @param size the size that will be used to set the extend, radius will be computed from it.
  37996. */
  37997. BoundingInfo2D.CreateFromSize = function (size) {
  37998. var r = new BoundingInfo2D();
  37999. BoundingInfo2D.CreateFromSizeToRef(size, r);
  38000. return r;
  38001. };
  38002. /**
  38003. * Create a BoundingInfo2D object from a given radius
  38004. * @param radius the radius to use, the extent will be computed from it.
  38005. */
  38006. BoundingInfo2D.CreateFromRadius = function (radius) {
  38007. var r = new BoundingInfo2D();
  38008. BoundingInfo2D.CreateFromRadiusToRef(radius, r);
  38009. return r;
  38010. };
  38011. /**
  38012. * Create a BoundingInfo2D object from a list of points.
  38013. * The resulted object will be the smallest bounding area that includes all the given points.
  38014. * @param points an array of points to compute the bounding object from.
  38015. */
  38016. BoundingInfo2D.CreateFromPoints = function (points) {
  38017. var r = new BoundingInfo2D();
  38018. BoundingInfo2D.CreateFromPointsToRef(points, r);
  38019. return r;
  38020. };
  38021. /**
  38022. * Update a BoundingInfo2D object using the given Size as input
  38023. * @param size the bounding data will be computed from this size.
  38024. * @param b must be a valid/allocated object, it will contain the result of the operation
  38025. */
  38026. BoundingInfo2D.CreateFromSizeToRef = function (size, b) {
  38027. if (!size) {
  38028. size = BABYLON.Size.Zero();
  38029. }
  38030. b.center.x = +size.width / 2;
  38031. b.center.y = +size.height / 2;
  38032. b.extent.x = b.center.x;
  38033. b.extent.y = b.center.y;
  38034. b.radius = b.extent.length();
  38035. };
  38036. /**
  38037. * Update a BoundingInfo2D object using the given radius as input
  38038. * @param radius the bounding data will be computed from this radius
  38039. * @param b must be a valid/allocated object, it will contain the result of the operation
  38040. */
  38041. BoundingInfo2D.CreateFromRadiusToRef = function (radius, b) {
  38042. b.center.x = b.center.y = 0;
  38043. var r = +radius;
  38044. b.extent.x = r;
  38045. b.extent.y = r;
  38046. b.radius = r;
  38047. };
  38048. /**
  38049. * Update a BoundingInfo2D object using the given points array as input
  38050. * @param points the point array to use to update the bounding data
  38051. * @param b must be a valid/allocated object, it will contain the result of the operation
  38052. */
  38053. BoundingInfo2D.CreateFromPointsToRef = function (points, b) {
  38054. var xmin = Number.MAX_VALUE, ymin = Number.MAX_VALUE, xmax = Number.MIN_VALUE, ymax = Number.MIN_VALUE;
  38055. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  38056. var p = points_1[_i];
  38057. xmin = Math.min(p.x, xmin);
  38058. xmax = Math.max(p.x, xmax);
  38059. ymin = Math.min(p.y, ymin);
  38060. ymax = Math.max(p.y, ymax);
  38061. }
  38062. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, b);
  38063. };
  38064. /**
  38065. * Update a BoundingInfo2D object using the given min/max values as input
  38066. * @param xmin the smallest x coordinate
  38067. * @param xmax the biggest x coordinate
  38068. * @param ymin the smallest y coordinate
  38069. * @param ymax the buggest y coordinate
  38070. * @param b must be a valid/allocated object, it will contain the result of the operation
  38071. */
  38072. BoundingInfo2D.CreateFromMinMaxToRef = function (xmin, xmax, ymin, ymax, b) {
  38073. var w = xmax - xmin;
  38074. var h = ymax - ymin;
  38075. b.center = new BABYLON.Vector2(xmin + w / 2, ymin + h / 2);
  38076. b.extent = new BABYLON.Vector2(xmax - b.center.x, ymax - b.center.y);
  38077. b.radius = b.extent.length();
  38078. };
  38079. /**
  38080. * Duplicate this instance and return a new one
  38081. * @return the duplicated instance
  38082. */
  38083. BoundingInfo2D.prototype.clone = function () {
  38084. var r = new BoundingInfo2D();
  38085. r.center = this.center.clone();
  38086. r.radius = this.radius;
  38087. r.extent = this.extent.clone();
  38088. return r;
  38089. };
  38090. BoundingInfo2D.prototype.clear = function () {
  38091. this.center.copyFromFloats(0, 0);
  38092. this.radius = 0;
  38093. this.extent.copyFromFloats(0, 0);
  38094. };
  38095. BoundingInfo2D.prototype.copyFrom = function (src) {
  38096. this.center.copyFrom(src.center);
  38097. this.radius = src.radius;
  38098. this.extent.copyFrom(src.extent);
  38099. };
  38100. /**
  38101. * return the max extend of the bounding info
  38102. */
  38103. BoundingInfo2D.prototype.max = function () {
  38104. var r = BABYLON.Vector2.Zero();
  38105. this.maxToRef(r);
  38106. return r;
  38107. };
  38108. /**
  38109. * Update a vector2 with the max extend of the bounding info
  38110. * @param result must be a valid/allocated vector2 that will contain the result of the operation
  38111. */
  38112. BoundingInfo2D.prototype.maxToRef = function (result) {
  38113. result.x = this.center.x + this.extent.x;
  38114. result.y = this.center.y + this.extent.y;
  38115. };
  38116. /**
  38117. * Apply a transformation matrix to this BoundingInfo2D and return a new instance containing the result
  38118. * @param matrix the transformation matrix to apply
  38119. * @return the new instance containing the result of the transformation applied on this BoundingInfo2D
  38120. */
  38121. BoundingInfo2D.prototype.transform = function (matrix) {
  38122. var r = new BoundingInfo2D();
  38123. this.transformToRef(matrix, r);
  38124. return r;
  38125. };
  38126. /**
  38127. * Compute the union of this BoundingInfo2D with a given one, returns a new BoundingInfo2D as a result
  38128. * @param other the second BoundingInfo2D to compute the union with this one
  38129. * @return a new instance containing the result of the union
  38130. */
  38131. BoundingInfo2D.prototype.union = function (other) {
  38132. var r = new BoundingInfo2D();
  38133. this.unionToRef(other, r);
  38134. return r;
  38135. };
  38136. /**
  38137. * Transform this BoundingInfo2D with a given matrix and store the result in an existing BoundingInfo2D instance.
  38138. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  38139. * @param matrix The matrix to use to compute the transformation
  38140. * @param result A VALID (i.e. allocated) BoundingInfo2D object where the result will be stored
  38141. */
  38142. BoundingInfo2D.prototype.transformToRef = function (matrix, result) {
  38143. // Construct a bounding box based on the extent values
  38144. var p = BoundingInfo2D._transform;
  38145. p[0].x = this.center.x + this.extent.x;
  38146. p[0].y = this.center.y + this.extent.y;
  38147. p[1].x = this.center.x + this.extent.x;
  38148. p[1].y = this.center.y - this.extent.y;
  38149. p[2].x = this.center.x - this.extent.x;
  38150. p[2].y = this.center.y - this.extent.y;
  38151. p[3].x = this.center.x - this.extent.x;
  38152. p[3].y = this.center.y + this.extent.y;
  38153. // Transform the four points of the bounding box with the matrix
  38154. for (var i = 0; i < 4; i++) {
  38155. BABYLON.Vector2.TransformToRef(p[i], matrix, p[i]);
  38156. }
  38157. BoundingInfo2D.CreateFromPointsToRef(p, result);
  38158. };
  38159. /**
  38160. * Compute the union of this BoundingInfo2D with another one and store the result in a third valid BoundingInfo2D object
  38161. * This is a GC friendly version, try to use it as much as possible, specially if your transformation is inside a loop, allocate the result object once for good outside of the loop and use it every time.
  38162. * @param other the second object used to compute the union
  38163. * @param result a VALID BoundingInfo2D instance (i.e. allocated) where the result will be stored
  38164. */
  38165. BoundingInfo2D.prototype.unionToRef = function (other, result) {
  38166. var xmax = Math.max(this.center.x + this.extent.x, other.center.x + other.extent.x);
  38167. var ymax = Math.max(this.center.y + this.extent.y, other.center.y + other.extent.y);
  38168. var xmin = Math.min(this.center.x - this.extent.x, other.center.x - other.extent.x);
  38169. var ymin = Math.min(this.center.y - this.extent.y, other.center.y - other.extent.y);
  38170. BoundingInfo2D.CreateFromMinMaxToRef(xmin, xmax, ymin, ymax, result);
  38171. };
  38172. /**
  38173. * Check if the given point is inside the BoundingInfo.
  38174. * The test is first made on the radius, then inside the rectangle described by the extent
  38175. * @param pickPosition the position to test
  38176. * @return true if the point is inside, false otherwise
  38177. */
  38178. BoundingInfo2D.prototype.doesIntersect = function (pickPosition) {
  38179. // is it inside the radius?
  38180. var pickLocal = pickPosition.subtract(this.center);
  38181. if (pickLocal.lengthSquared() <= (this.radius * this.radius)) {
  38182. // is it inside the rectangle?
  38183. return ((Math.abs(pickLocal.x) <= this.extent.x) && (Math.abs(pickLocal.y) <= this.extent.y));
  38184. }
  38185. return false;
  38186. };
  38187. BoundingInfo2D._transform = new Array(BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero(), BABYLON.Vector2.Zero());
  38188. return BoundingInfo2D;
  38189. }());
  38190. BABYLON.BoundingInfo2D = BoundingInfo2D;
  38191. })(BABYLON || (BABYLON = {}));
  38192. var BABYLON;
  38193. (function (BABYLON) {
  38194. /**
  38195. * Base class implementing the ILocable interface.
  38196. * The particularity of this class is to call the protected onLock() method when the instance is about to be locked for good.
  38197. */
  38198. var LockableBase = (function () {
  38199. function LockableBase() {
  38200. }
  38201. LockableBase.prototype.isLocked = function () {
  38202. return this._isLocked;
  38203. };
  38204. LockableBase.prototype.lock = function () {
  38205. if (this._isLocked) {
  38206. return true;
  38207. }
  38208. this.onLock();
  38209. this._isLocked = true;
  38210. return false;
  38211. };
  38212. /**
  38213. * Protected handler that will be called when the instance is about to be locked.
  38214. */
  38215. LockableBase.prototype.onLock = function () {
  38216. };
  38217. return LockableBase;
  38218. }());
  38219. BABYLON.LockableBase = LockableBase;
  38220. var SolidColorBrush2D = (function (_super) {
  38221. __extends(SolidColorBrush2D, _super);
  38222. function SolidColorBrush2D(color, lock) {
  38223. if (lock === void 0) { lock = false; }
  38224. _super.call(this);
  38225. this._color = color;
  38226. if (lock) {
  38227. {
  38228. this.lock();
  38229. }
  38230. }
  38231. }
  38232. /**
  38233. * Return true if the brush is transparent, false if it's totally opaque
  38234. */
  38235. SolidColorBrush2D.prototype.isTransparent = function () {
  38236. return this._color && this._color.a < 1.0;
  38237. };
  38238. Object.defineProperty(SolidColorBrush2D.prototype, "color", {
  38239. /**
  38240. * The color used by this instance to render
  38241. * @returns the color object. Note that it's not a clone of the actual object stored in the instance so you MUST NOT modify it, otherwise unexpected behavior might occurs.
  38242. */
  38243. get: function () {
  38244. return this._color;
  38245. },
  38246. set: function (value) {
  38247. if (this.isLocked()) {
  38248. return;
  38249. }
  38250. this._color = value;
  38251. },
  38252. enumerable: true,
  38253. configurable: true
  38254. });
  38255. /**
  38256. * Return a unique identifier of the instance, which is simply the hexadecimal representation (CSS Style) of the solid color.
  38257. */
  38258. SolidColorBrush2D.prototype.toString = function () {
  38259. return this._color.toHexString();
  38260. };
  38261. SolidColorBrush2D = __decorate([
  38262. BABYLON.className("SolidColorBrush2D")
  38263. ], SolidColorBrush2D);
  38264. return SolidColorBrush2D;
  38265. }(LockableBase));
  38266. BABYLON.SolidColorBrush2D = SolidColorBrush2D;
  38267. var GradientColorBrush2D = (function (_super) {
  38268. __extends(GradientColorBrush2D, _super);
  38269. function GradientColorBrush2D(color1, color2, translation, rotation, scale, lock) {
  38270. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  38271. if (rotation === void 0) { rotation = 0; }
  38272. if (scale === void 0) { scale = 1; }
  38273. if (lock === void 0) { lock = false; }
  38274. _super.call(this);
  38275. this._color1 = color1;
  38276. this._color2 = color2;
  38277. this._translation = translation;
  38278. this._rotation = rotation;
  38279. this._scale = scale;
  38280. if (lock) {
  38281. this.lock();
  38282. }
  38283. }
  38284. /**
  38285. * Return true if the brush is transparent, false if it's totally opaque
  38286. */
  38287. GradientColorBrush2D.prototype.isTransparent = function () {
  38288. return (this._color1 && this._color1.a < 1.0) || (this._color2 && this._color2.a < 1.0);
  38289. };
  38290. Object.defineProperty(GradientColorBrush2D.prototype, "color1", {
  38291. /**
  38292. * First color, the blend will start from this color
  38293. */
  38294. get: function () {
  38295. return this._color1;
  38296. },
  38297. set: function (value) {
  38298. if (this.isLocked()) {
  38299. return;
  38300. }
  38301. this._color1 = value;
  38302. },
  38303. enumerable: true,
  38304. configurable: true
  38305. });
  38306. Object.defineProperty(GradientColorBrush2D.prototype, "color2", {
  38307. /**
  38308. * Second color, the blend will end to this color
  38309. */
  38310. get: function () {
  38311. return this._color2;
  38312. },
  38313. set: function (value) {
  38314. if (this.isLocked()) {
  38315. return;
  38316. }
  38317. this._color2 = value;
  38318. },
  38319. enumerable: true,
  38320. configurable: true
  38321. });
  38322. Object.defineProperty(GradientColorBrush2D.prototype, "translation", {
  38323. /**
  38324. * Translation vector to apply on the blend
  38325. * Default is [0;0]
  38326. */
  38327. get: function () {
  38328. return this._translation;
  38329. },
  38330. set: function (value) {
  38331. if (this.isLocked()) {
  38332. return;
  38333. }
  38334. this._translation = value;
  38335. },
  38336. enumerable: true,
  38337. configurable: true
  38338. });
  38339. Object.defineProperty(GradientColorBrush2D.prototype, "rotation", {
  38340. /**
  38341. * Rotation in radian to apply to the brush
  38342. * Default direction of the brush is vertical, you can change this using this property.
  38343. * Default is 0.
  38344. */
  38345. get: function () {
  38346. return this._rotation;
  38347. },
  38348. set: function (value) {
  38349. if (this.isLocked()) {
  38350. return;
  38351. }
  38352. this._rotation = value;
  38353. },
  38354. enumerable: true,
  38355. configurable: true
  38356. });
  38357. Object.defineProperty(GradientColorBrush2D.prototype, "scale", {
  38358. /**
  38359. * Scale factor to apply to the gradient.
  38360. * Default is 1: no scale.
  38361. */
  38362. get: function () {
  38363. return this._scale;
  38364. },
  38365. set: function (value) {
  38366. if (this.isLocked()) {
  38367. return;
  38368. }
  38369. this._scale = value;
  38370. },
  38371. enumerable: true,
  38372. configurable: true
  38373. });
  38374. /**
  38375. * Return a string describing the brush
  38376. */
  38377. GradientColorBrush2D.prototype.toString = function () {
  38378. return "C1:" + this._color1 + ";C2:" + this._color2 + ";T:" + this._translation.toString() + ";R:" + this._rotation + ";S:" + this._scale + ";";
  38379. };
  38380. /**
  38381. * Build a unique key string for the given parameters
  38382. */
  38383. GradientColorBrush2D.BuildKey = function (color1, color2, translation, rotation, scale) {
  38384. return "C1:" + color1 + ";C2:" + color2 + ";T:" + translation.toString() + ";R:" + rotation + ";S:" + scale + ";";
  38385. };
  38386. GradientColorBrush2D = __decorate([
  38387. BABYLON.className("GradientColorBrush2D")
  38388. ], GradientColorBrush2D);
  38389. return GradientColorBrush2D;
  38390. }(LockableBase));
  38391. BABYLON.GradientColorBrush2D = GradientColorBrush2D;
  38392. })(BABYLON || (BABYLON = {}));
  38393. var BABYLON;
  38394. (function (BABYLON) {
  38395. var Prim2DClassInfo = (function () {
  38396. function Prim2DClassInfo() {
  38397. }
  38398. return Prim2DClassInfo;
  38399. }());
  38400. BABYLON.Prim2DClassInfo = Prim2DClassInfo;
  38401. var Prim2DPropInfo = (function () {
  38402. function Prim2DPropInfo() {
  38403. }
  38404. Prim2DPropInfo.PROPKIND_MODEL = 1;
  38405. Prim2DPropInfo.PROPKIND_INSTANCE = 2;
  38406. Prim2DPropInfo.PROPKIND_DYNAMIC = 3;
  38407. return Prim2DPropInfo;
  38408. }());
  38409. BABYLON.Prim2DPropInfo = Prim2DPropInfo;
  38410. /**
  38411. * Custom type of the propertyChanged observable
  38412. */
  38413. var PropertyChangedInfo = (function () {
  38414. function PropertyChangedInfo() {
  38415. }
  38416. return PropertyChangedInfo;
  38417. }());
  38418. BABYLON.PropertyChangedInfo = PropertyChangedInfo;
  38419. var ClassTreeInfo = (function () {
  38420. function ClassTreeInfo(baseClass, type, classContentFactory) {
  38421. this._baseClass = baseClass;
  38422. this._type = type;
  38423. this._subClasses = new Array();
  38424. this._levelContent = new BABYLON.StringDictionary();
  38425. this._classContentFactory = classContentFactory;
  38426. }
  38427. Object.defineProperty(ClassTreeInfo.prototype, "classContent", {
  38428. get: function () {
  38429. if (!this._classContent) {
  38430. this._classContent = this._classContentFactory(this._baseClass ? this._baseClass.classContent : null);
  38431. }
  38432. return this._classContent;
  38433. },
  38434. enumerable: true,
  38435. configurable: true
  38436. });
  38437. Object.defineProperty(ClassTreeInfo.prototype, "type", {
  38438. get: function () {
  38439. return this._type;
  38440. },
  38441. enumerable: true,
  38442. configurable: true
  38443. });
  38444. Object.defineProperty(ClassTreeInfo.prototype, "levelContent", {
  38445. get: function () {
  38446. return this._levelContent;
  38447. },
  38448. enumerable: true,
  38449. configurable: true
  38450. });
  38451. Object.defineProperty(ClassTreeInfo.prototype, "fullContent", {
  38452. get: function () {
  38453. if (!this._fullContent) {
  38454. var dic_1 = new BABYLON.StringDictionary();
  38455. var curLevel = this;
  38456. while (curLevel) {
  38457. curLevel.levelContent.forEach(function (k, v) { return dic_1.add(k, v); });
  38458. curLevel = curLevel._baseClass;
  38459. }
  38460. this._fullContent = dic_1;
  38461. }
  38462. return this._fullContent;
  38463. },
  38464. enumerable: true,
  38465. configurable: true
  38466. });
  38467. ClassTreeInfo.prototype.getLevelOf = function (type) {
  38468. // Are we already there?
  38469. if (type === this._type) {
  38470. return this;
  38471. }
  38472. var baseProto = Object.getPrototypeOf(type);
  38473. var curProtoContent = this.getOrAddType(Object.getPrototypeOf(baseProto), baseProto);
  38474. if (!curProtoContent) {
  38475. this.getLevelOf(baseProto);
  38476. }
  38477. return this.getOrAddType(baseProto, type);
  38478. };
  38479. ClassTreeInfo.prototype.getOrAddType = function (baseType, type) {
  38480. // Are we at the level corresponding to the baseType?
  38481. // If so, get or add the level we're looking for
  38482. if (baseType === this._type) {
  38483. for (var _i = 0, _a = this._subClasses; _i < _a.length; _i++) {
  38484. var subType = _a[_i];
  38485. if (subType.type === type) {
  38486. return subType.node;
  38487. }
  38488. }
  38489. var node = new ClassTreeInfo(this, type, this._classContentFactory);
  38490. var info = { type: type, node: node };
  38491. this._subClasses.push(info);
  38492. return info.node;
  38493. }
  38494. // Recurse down to keep looking for the node corresponding to the baseTypeName
  38495. for (var _b = 0, _c = this._subClasses; _b < _c.length; _b++) {
  38496. var subType = _c[_b];
  38497. var info = subType.node.getOrAddType(baseType, type);
  38498. if (info) {
  38499. return info;
  38500. }
  38501. }
  38502. return null;
  38503. };
  38504. ClassTreeInfo.get = function (type) {
  38505. var dic = type["__classTreeInfo"];
  38506. if (!dic) {
  38507. return null;
  38508. }
  38509. return dic.getLevelOf(type);
  38510. };
  38511. ClassTreeInfo.getOrRegister = function (type, classContentFactory) {
  38512. var dic = type["__classTreeInfo"];
  38513. if (!dic) {
  38514. dic = new ClassTreeInfo(null, type, classContentFactory);
  38515. type["__classTreeInfo"] = dic;
  38516. }
  38517. return dic;
  38518. };
  38519. return ClassTreeInfo;
  38520. }());
  38521. BABYLON.ClassTreeInfo = ClassTreeInfo;
  38522. var SmartPropertyPrim = (function () {
  38523. function SmartPropertyPrim() {
  38524. this._flags = 0;
  38525. this._modelKey = null;
  38526. this._instanceDirtyFlags = 0;
  38527. this._levelBoundingInfo = new BABYLON.BoundingInfo2D();
  38528. this.animations = new Array();
  38529. }
  38530. Object.defineProperty(SmartPropertyPrim.prototype, "isDisposed", {
  38531. /**
  38532. * Check if the object is disposed or not.
  38533. * @returns true if the object is dispose, false otherwise.
  38534. */
  38535. get: function () {
  38536. return this._isFlagSet(SmartPropertyPrim.flagIsDisposed);
  38537. },
  38538. enumerable: true,
  38539. configurable: true
  38540. });
  38541. /**
  38542. * Disposable pattern, this method must be overloaded by derived types in order to clean up hardware related resources.
  38543. * @returns false if the object is already dispose, true otherwise. Your implementation must call super.dispose() and check for a false return and return immediately if it's the case.
  38544. */
  38545. SmartPropertyPrim.prototype.dispose = function () {
  38546. if (this.isDisposed) {
  38547. return false;
  38548. }
  38549. // Don't set to null, it may upset somebody...
  38550. this.animations.splice(0);
  38551. this._setFlags(SmartPropertyPrim.flagIsDisposed);
  38552. return true;
  38553. };
  38554. /**
  38555. * Returns as a new array populated with the Animatable used by the primitive. Must be overloaded by derived primitives.
  38556. * Look at Sprite2D for more information
  38557. */
  38558. SmartPropertyPrim.prototype.getAnimatables = function () {
  38559. return new Array();
  38560. };
  38561. Object.defineProperty(SmartPropertyPrim.prototype, "modelKey", {
  38562. /**
  38563. * Property giving the Model Key associated to the property.
  38564. * This value is constructed from the type of the primitive and all the name/value of its properties declared with the modelLevelProperty decorator
  38565. * @returns the model key string.
  38566. */
  38567. get: function () {
  38568. var _this = this;
  38569. // No need to compute it?
  38570. if (!this._isFlagSet(SmartPropertyPrim.flagModelDirty) && this._modelKey) {
  38571. return this._modelKey;
  38572. }
  38573. var modelKey = "Class:" + BABYLON.Tools.getClassName(this) + ";";
  38574. var propDic = this.propDic;
  38575. propDic.forEach(function (k, v) {
  38576. if (v.kind === Prim2DPropInfo.PROPKIND_MODEL) {
  38577. var propVal = _this[v.name];
  38578. // Special case, array, this WON'T WORK IN ALL CASES, all entries have to be of the same type and it must be a BJS well known one
  38579. if (propVal && propVal.constructor === Array) {
  38580. var firstVal = propVal[0];
  38581. if (!firstVal) {
  38582. propVal = 0;
  38583. }
  38584. else {
  38585. propVal = BABYLON.Tools.hashCodeFromStream(BABYLON.Tools.arrayOrStringFeeder(propVal));
  38586. }
  38587. }
  38588. modelKey += v.name + ":" + ((propVal != null) ? ((v.typeLevelCompare) ? BABYLON.Tools.getClassName(propVal) : propVal.toString()) : "[null]") + ";";
  38589. }
  38590. });
  38591. this._clearFlags(SmartPropertyPrim.flagModelDirty);
  38592. this._modelKey = modelKey;
  38593. return modelKey;
  38594. },
  38595. enumerable: true,
  38596. configurable: true
  38597. });
  38598. Object.defineProperty(SmartPropertyPrim.prototype, "isDirty", {
  38599. /**
  38600. * States if the Primitive is dirty and should be rendered again next time.
  38601. * @returns true is dirty, false otherwise
  38602. */
  38603. get: function () {
  38604. return (this._instanceDirtyFlags !== 0) || this._areSomeFlagsSet(SmartPropertyPrim.flagModelDirty | SmartPropertyPrim.flagPositioningDirty | SmartPropertyPrim.flagLayoutDirty);
  38605. },
  38606. enumerable: true,
  38607. configurable: true
  38608. });
  38609. Object.defineProperty(SmartPropertyPrim.prototype, "propDic", {
  38610. /**
  38611. * Access the dictionary of properties metadata. Only properties decorated with XXXXLevelProperty are concerned
  38612. * @returns the dictionary, the key is the property name as declared in Javascript, the value is the metadata object
  38613. */
  38614. get: function () {
  38615. if (!this._propInfo) {
  38616. var cti = ClassTreeInfo.get(Object.getPrototypeOf(this));
  38617. if (!cti) {
  38618. throw new Error("Can't access the propDic member in class definition, is this class SmartPropertyPrim based?");
  38619. }
  38620. this._propInfo = cti.fullContent;
  38621. }
  38622. return this._propInfo;
  38623. },
  38624. enumerable: true,
  38625. configurable: true
  38626. });
  38627. SmartPropertyPrim._createPropInfo = function (target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind) {
  38628. var dic = ClassTreeInfo.getOrRegister(target, function () { return new Prim2DClassInfo(); });
  38629. var node = dic.getLevelOf(target);
  38630. var propInfo = node.levelContent.get(propId.toString());
  38631. if (propInfo) {
  38632. throw new Error("The ID " + propId + " is already taken by another property declaration named: " + propInfo.name);
  38633. }
  38634. // Create, setup and add the PropInfo object to our prop dictionary
  38635. propInfo = new Prim2DPropInfo();
  38636. propInfo.id = propId;
  38637. propInfo.flagId = Math.pow(2, propId);
  38638. propInfo.kind = kind;
  38639. propInfo.name = propName;
  38640. propInfo.dirtyBoundingInfo = dirtyBoundingInfo;
  38641. propInfo.dirtyParentBoundingInfo = dirtyParentBoundingBox;
  38642. propInfo.typeLevelCompare = typeLevelCompare;
  38643. node.levelContent.add(propName, propInfo);
  38644. return propInfo;
  38645. };
  38646. SmartPropertyPrim._checkUnchanged = function (curValue, newValue) {
  38647. // Nothing to nothing: nothing to do!
  38648. if ((curValue === null && newValue === null) || (curValue === undefined && newValue === undefined)) {
  38649. return true;
  38650. }
  38651. // Check value unchanged
  38652. if ((curValue != null) && (newValue != null)) {
  38653. if (typeof (curValue.equals) == "function") {
  38654. if (curValue.equals(newValue)) {
  38655. return true;
  38656. }
  38657. }
  38658. else {
  38659. if (curValue === newValue) {
  38660. return true;
  38661. }
  38662. }
  38663. }
  38664. return false;
  38665. };
  38666. SmartPropertyPrim.prototype.markAsDirty = function (propertyName) {
  38667. if (this.isDisposed) {
  38668. return;
  38669. }
  38670. var i = propertyName.indexOf(".");
  38671. if (i !== -1) {
  38672. propertyName = propertyName.substr(0, i);
  38673. }
  38674. var propInfo = this.propDic.get(propertyName);
  38675. if (!propInfo) {
  38676. return;
  38677. }
  38678. var newValue = this[propertyName];
  38679. this._handlePropChanged(undefined, newValue, propertyName, propInfo, propInfo.typeLevelCompare);
  38680. };
  38681. SmartPropertyPrim.prototype._boundingBoxDirty = function () {
  38682. this._setFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  38683. // Escalate the dirty flag in the instance hierarchy, stop when a renderable group is found or at the end
  38684. if (this instanceof BABYLON.Prim2DBase) {
  38685. var curprim = this;
  38686. while (curprim) {
  38687. curprim._setFlags(SmartPropertyPrim.flagBoundingInfoDirty);
  38688. if (curprim.isSizeAuto) {
  38689. curprim.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  38690. curprim._setFlags(SmartPropertyPrim.flagPositioningDirty);
  38691. }
  38692. if (curprim instanceof BABYLON.Group2D) {
  38693. if (curprim.isRenderableGroup) {
  38694. break;
  38695. }
  38696. }
  38697. curprim = curprim.parent;
  38698. }
  38699. }
  38700. };
  38701. SmartPropertyPrim.prototype._handlePropChanged = function (curValue, newValue, propName, propInfo, typeLevelCompare) {
  38702. // If the property change also dirty the boundingInfo, update the boundingInfo dirty flags
  38703. if (propInfo.dirtyBoundingInfo) {
  38704. this._boundingBoxDirty();
  38705. }
  38706. else if (propInfo.dirtyParentBoundingInfo) {
  38707. var p = this._parent;
  38708. if (p != null) {
  38709. p._boundingBoxDirty();
  38710. }
  38711. }
  38712. // Trigger property changed
  38713. var info = SmartPropertyPrim.propChangedInfo;
  38714. info.oldValue = curValue;
  38715. info.newValue = newValue;
  38716. info.propertyName = propName;
  38717. var propMask = propInfo.flagId;
  38718. this.propertyChanged.notifyObservers(info, propMask);
  38719. // If the property belong to a group, check if it's a cached one, and dirty its render sprite accordingly
  38720. if (this instanceof BABYLON.Group2D) {
  38721. this.handleGroupChanged(propInfo);
  38722. }
  38723. // Check for parent layout dirty
  38724. if (this instanceof BABYLON.Prim2DBase) {
  38725. var p = this._parent;
  38726. if (p != null && p.layoutEngine && (p.layoutEngine.layoutDirtyOnPropertyChangedMask & propInfo.flagId) !== 0) {
  38727. p._setLayoutDirty();
  38728. }
  38729. }
  38730. // For type level compare, if there's a change of type it's a change of model, otherwise we issue an instance change
  38731. var instanceDirty = false;
  38732. if (typeLevelCompare && curValue != null && newValue != null) {
  38733. var cvProto = curValue.__proto__;
  38734. var nvProto = newValue.__proto__;
  38735. instanceDirty = (cvProto === nvProto);
  38736. }
  38737. // Set the dirty flags
  38738. if (!instanceDirty && (propInfo.kind === Prim2DPropInfo.PROPKIND_MODEL)) {
  38739. if (!this.isDirty) {
  38740. this._setFlags(SmartPropertyPrim.flagModelDirty);
  38741. }
  38742. }
  38743. else if (instanceDirty || (propInfo.kind === Prim2DPropInfo.PROPKIND_INSTANCE) || (propInfo.kind === Prim2DPropInfo.PROPKIND_DYNAMIC)) {
  38744. this.onPrimitivePropertyDirty(propMask);
  38745. }
  38746. };
  38747. SmartPropertyPrim.prototype.onPrimitivePropertyDirty = function (propFlagId) {
  38748. this.onPrimBecomesDirty();
  38749. this._instanceDirtyFlags |= propFlagId;
  38750. };
  38751. SmartPropertyPrim.prototype.handleGroupChanged = function (prop) {
  38752. };
  38753. /**
  38754. * Check if a given set of properties are dirty or not.
  38755. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  38756. * @return true if at least one property is dirty, false if none of them are.
  38757. */
  38758. SmartPropertyPrim.prototype.checkPropertiesDirty = function (flags) {
  38759. return (this._instanceDirtyFlags & flags) !== 0;
  38760. };
  38761. /**
  38762. * Clear a given set of properties.
  38763. * @param flags a ORed combination of Prim2DPropInfo.flagId values
  38764. * @return the new set of property still marked as dirty
  38765. */
  38766. SmartPropertyPrim.prototype.clearPropertiesDirty = function (flags) {
  38767. this._instanceDirtyFlags &= ~flags;
  38768. return this._instanceDirtyFlags;
  38769. };
  38770. SmartPropertyPrim.prototype._resetPropertiesDirty = function () {
  38771. this._instanceDirtyFlags = 0;
  38772. this._clearFlags(SmartPropertyPrim.flagPrimInDirtyList);
  38773. };
  38774. Object.defineProperty(SmartPropertyPrim.prototype, "levelBoundingInfo", {
  38775. /**
  38776. * Retrieve the boundingInfo for this Primitive, computed based on the primitive itself and NOT its children
  38777. */
  38778. get: function () {
  38779. if (this._isFlagSet(SmartPropertyPrim.flagLevelBoundingInfoDirty)) {
  38780. this.updateLevelBoundingInfo();
  38781. this._clearFlags(SmartPropertyPrim.flagLevelBoundingInfoDirty);
  38782. }
  38783. return this._levelBoundingInfo;
  38784. },
  38785. enumerable: true,
  38786. configurable: true
  38787. });
  38788. /**
  38789. * This method must be overridden by a given Primitive implementation to compute its boundingInfo
  38790. */
  38791. SmartPropertyPrim.prototype.updateLevelBoundingInfo = function () {
  38792. };
  38793. /**
  38794. * Property method called when the Primitive becomes dirty
  38795. */
  38796. SmartPropertyPrim.prototype.onPrimBecomesDirty = function () {
  38797. };
  38798. SmartPropertyPrim._hookProperty = function (propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, kind) {
  38799. return function (target, propName, descriptor) {
  38800. var propInfo = SmartPropertyPrim._createPropInfo(target, propName, propId, dirtyBoundingInfo, dirtyParentBoundingBox, typeLevelCompare, kind);
  38801. if (piStore) {
  38802. piStore(propInfo);
  38803. }
  38804. var getter = descriptor.get, setter = descriptor.set;
  38805. // Overload the property setter implementation to add our own logic
  38806. descriptor.set = function (val) {
  38807. // check for disposed first, do nothing
  38808. if (this.isDisposed) {
  38809. return;
  38810. }
  38811. var curVal = getter.call(this);
  38812. if (SmartPropertyPrim._checkUnchanged(curVal, val)) {
  38813. return;
  38814. }
  38815. // Cast the object we're working one
  38816. var prim = this;
  38817. // Change the value
  38818. setter.call(this, val);
  38819. // Notify change, dirty flags update
  38820. prim._handlePropChanged(curVal, val, propName, propInfo, typeLevelCompare);
  38821. };
  38822. };
  38823. };
  38824. /**
  38825. * Add an externally attached data from its key.
  38826. * This method call will fail and return false, if such key already exists.
  38827. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  38828. * @param key the unique key that identifies the data
  38829. * @param data the data object to associate to the key for this Engine instance
  38830. * @return true if no such key were already present and the data was added successfully, false otherwise
  38831. */
  38832. SmartPropertyPrim.prototype.addExternalData = function (key, data) {
  38833. if (!this._externalData) {
  38834. this._externalData = new BABYLON.StringDictionary();
  38835. }
  38836. return this._externalData.add(key, data);
  38837. };
  38838. /**
  38839. * Get an externally attached data from its key
  38840. * @param key the unique key that identifies the data
  38841. * @return the associated data, if present (can be null), or undefined if not present
  38842. */
  38843. SmartPropertyPrim.prototype.getExternalData = function (key) {
  38844. if (!this._externalData) {
  38845. return null;
  38846. }
  38847. return this._externalData.get(key);
  38848. };
  38849. /**
  38850. * Get an externally attached data from its key, create it using a factory if it's not already present
  38851. * @param key the unique key that identifies the data
  38852. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  38853. * @return the associated data, can be null if the factory returned null.
  38854. */
  38855. SmartPropertyPrim.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  38856. if (!this._externalData) {
  38857. this._externalData = new BABYLON.StringDictionary();
  38858. }
  38859. return this._externalData.getOrAddWithFactory(key, factory);
  38860. };
  38861. /**
  38862. * Remove an externally attached data from the Engine instance
  38863. * @param key the unique key that identifies the data
  38864. * @return true if the data was successfully removed, false if it doesn't exist
  38865. */
  38866. SmartPropertyPrim.prototype.removeExternalData = function (key) {
  38867. if (!this._externalData) {
  38868. return false;
  38869. }
  38870. return this._externalData.remove(key);
  38871. };
  38872. /**
  38873. * Check if a given flag is set
  38874. * @param flag the flag value
  38875. * @return true if set, false otherwise
  38876. */
  38877. SmartPropertyPrim.prototype._isFlagSet = function (flag) {
  38878. return (this._flags & flag) !== 0;
  38879. };
  38880. /**
  38881. * Check if all given flags are set
  38882. * @param flags the flags ORed
  38883. * @return true if all the flags are set, false otherwise
  38884. */
  38885. SmartPropertyPrim.prototype._areAllFlagsSet = function (flags) {
  38886. return (this._flags & flags) === flags;
  38887. };
  38888. /**
  38889. * Check if at least one flag of the given flags is set
  38890. * @param flags the flags ORed
  38891. * @return true if at least one flag is set, false otherwise
  38892. */
  38893. SmartPropertyPrim.prototype._areSomeFlagsSet = function (flags) {
  38894. return (this._flags & flags) !== 0;
  38895. };
  38896. /**
  38897. * Clear the given flags
  38898. * @param flags the flags to clear
  38899. */
  38900. SmartPropertyPrim.prototype._clearFlags = function (flags) {
  38901. this._flags &= ~flags;
  38902. };
  38903. /**
  38904. * Set the given flags to true state
  38905. * @param flags the flags ORed to set
  38906. * @return the flags state before this call
  38907. */
  38908. SmartPropertyPrim.prototype._setFlags = function (flags) {
  38909. var cur = this._flags;
  38910. this._flags |= flags;
  38911. return cur;
  38912. };
  38913. /**
  38914. * Change the state of the given flags
  38915. * @param flags the flags ORed to change
  38916. * @param state true to set them, false to clear them
  38917. */
  38918. SmartPropertyPrim.prototype._changeFlags = function (flags, state) {
  38919. if (state) {
  38920. this._flags |= flags;
  38921. }
  38922. else {
  38923. this._flags &= ~flags;
  38924. }
  38925. };
  38926. SmartPropertyPrim.propChangedInfo = new PropertyChangedInfo();
  38927. SmartPropertyPrim.flagIsDisposed = 0x0000001; // set if the object is already disposed
  38928. SmartPropertyPrim.flagLevelBoundingInfoDirty = 0x0000002; // set if the primitive's level bounding box (not including children) is dirty
  38929. SmartPropertyPrim.flagModelDirty = 0x0000004; // set if the model must be changed
  38930. SmartPropertyPrim.flagLayoutDirty = 0x0000008; // set if the layout must be computed
  38931. SmartPropertyPrim.flagLevelVisible = 0x0000010; // set if the primitive is set as visible for its level only
  38932. SmartPropertyPrim.flagBoundingInfoDirty = 0x0000020; // set if the primitive's overall bounding box (including children) is dirty
  38933. SmartPropertyPrim.flagIsPickable = 0x0000040; // set if the primitive can be picked during interaction
  38934. SmartPropertyPrim.flagIsVisible = 0x0000080; // set if the primitive is concretely visible (use the levelVisible of parents)
  38935. SmartPropertyPrim.flagVisibilityChanged = 0x0000100; // set if there was a transition between visible/hidden status
  38936. SmartPropertyPrim.flagPositioningDirty = 0x0000200; // set if the primitive positioning must be computed
  38937. SmartPropertyPrim.flagTrackedGroup = 0x0000400; // set if the group2D is tracking a scene node
  38938. SmartPropertyPrim.flagWorldCacheChanged = 0x0000800; // set if the cached bitmap of a world space canvas changed
  38939. SmartPropertyPrim.flagChildrenFlatZOrder = 0x0001000; // set if all the children (direct and indirect) will share the same Z-Order
  38940. SmartPropertyPrim.flagZOrderDirty = 0x0002000; // set if the Z-Order for this prim and its children must be recomputed
  38941. SmartPropertyPrim.flagActualOpacityDirty = 0x0004000; // set if the actualOpactity should be recomputed
  38942. SmartPropertyPrim.flagPrimInDirtyList = 0x0008000; // set if the primitive is in the primDirtyList
  38943. SmartPropertyPrim.flagIsContainer = 0x0010000; // set if the primitive is a container
  38944. SmartPropertyPrim = __decorate([
  38945. BABYLON.className("SmartPropertyPrim")
  38946. ], SmartPropertyPrim);
  38947. return SmartPropertyPrim;
  38948. }());
  38949. BABYLON.SmartPropertyPrim = SmartPropertyPrim;
  38950. function modelLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38951. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38952. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38953. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38954. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_MODEL);
  38955. }
  38956. BABYLON.modelLevelProperty = modelLevelProperty;
  38957. function instanceLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38958. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38959. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38960. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38961. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_INSTANCE);
  38962. }
  38963. BABYLON.instanceLevelProperty = instanceLevelProperty;
  38964. function dynamicLevelProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox) {
  38965. if (typeLevelCompare === void 0) { typeLevelCompare = false; }
  38966. if (dirtyBoundingInfo === void 0) { dirtyBoundingInfo = false; }
  38967. if (dirtyParentBoundingBox === void 0) { dirtyParentBoundingBox = false; }
  38968. return SmartPropertyPrim._hookProperty(propId, piStore, typeLevelCompare, dirtyBoundingInfo, dirtyParentBoundingBox, Prim2DPropInfo.PROPKIND_DYNAMIC);
  38969. }
  38970. BABYLON.dynamicLevelProperty = dynamicLevelProperty;
  38971. })(BABYLON || (BABYLON = {}));
  38972. var BABYLON;
  38973. (function (BABYLON) {
  38974. var PrepareRender2DContext = (function () {
  38975. function PrepareRender2DContext() {
  38976. this.forceRefreshPrimitive = false;
  38977. }
  38978. return PrepareRender2DContext;
  38979. }());
  38980. BABYLON.PrepareRender2DContext = PrepareRender2DContext;
  38981. var Render2DContext = (function () {
  38982. function Render2DContext(renderMode) {
  38983. this._renderMode = renderMode;
  38984. this.useInstancing = false;
  38985. this.groupInfoPartData = null;
  38986. this.partDataStartIndex = this.partDataEndIndex = null;
  38987. this.instancedBuffers = null;
  38988. }
  38989. Object.defineProperty(Render2DContext.prototype, "renderMode", {
  38990. /**
  38991. * Define which render Mode should be used to render the primitive: one of Render2DContext.RenderModeXxxx property
  38992. */
  38993. get: function () {
  38994. return this._renderMode;
  38995. },
  38996. enumerable: true,
  38997. configurable: true
  38998. });
  38999. Object.defineProperty(Render2DContext, "RenderModeOpaque", {
  39000. /**
  39001. * The set of primitives to render is opaque.
  39002. * This is the first rendering pass. All Opaque primitives are rendered. Depth Compare and Write are both enabled.
  39003. */
  39004. get: function () {
  39005. return Render2DContext._renderModeOpaque;
  39006. },
  39007. enumerable: true,
  39008. configurable: true
  39009. });
  39010. Object.defineProperty(Render2DContext, "RenderModeAlphaTest", {
  39011. /**
  39012. * The set of primitives to render is using Alpha Test (aka masking).
  39013. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeOpaque and is depth independent (i.e. primitives are not sorted by depth). Depth Compare and Write are both enabled.
  39014. */
  39015. get: function () {
  39016. return Render2DContext._renderModeAlphaTest;
  39017. },
  39018. enumerable: true,
  39019. configurable: true
  39020. });
  39021. Object.defineProperty(Render2DContext, "RenderModeTransparent", {
  39022. /**
  39023. * The set of primitives to render is transparent.
  39024. * Alpha Blend is enabled, the AlphaMode must be manually set, the render occurs after the RenderModeAlphaTest and is depth dependent (i.e. primitives are stored by depth and rendered back to front). Depth Compare is on, but Depth write is Off.
  39025. */
  39026. get: function () {
  39027. return Render2DContext._renderModeTransparent;
  39028. },
  39029. enumerable: true,
  39030. configurable: true
  39031. });
  39032. Render2DContext._renderModeOpaque = 1;
  39033. Render2DContext._renderModeAlphaTest = 2;
  39034. Render2DContext._renderModeTransparent = 3;
  39035. return Render2DContext;
  39036. }());
  39037. BABYLON.Render2DContext = Render2DContext;
  39038. /**
  39039. * This class store information for the pointerEventObservable Observable.
  39040. * The Observable is divided into many sub events (using the Mask feature of the Observable pattern): PointerOver, PointerEnter, PointerDown, PointerMouseWheel, PointerMove, PointerUp, PointerDown, PointerLeave, PointerGotCapture and PointerLostCapture.
  39041. */
  39042. var PrimitivePointerInfo = (function () {
  39043. function PrimitivePointerInfo() {
  39044. this.primitivePointerPos = BABYLON.Vector2.Zero();
  39045. this.tilt = BABYLON.Vector2.Zero();
  39046. this.cancelBubble = false;
  39047. }
  39048. Object.defineProperty(PrimitivePointerInfo, "PointerOver", {
  39049. // The behavior is based on the HTML specifications of the Pointer Events (https://www.w3.org/TR/pointerevents/#list-of-pointer-events). This is not 100% compliant and not meant to be, but still, it's based on these specs for most use cases to be programmed the same way (as closest as possible) as it would have been in HTML.
  39050. /**
  39051. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive.
  39052. * Bubbles: yes
  39053. */
  39054. get: function () {
  39055. return PrimitivePointerInfo._pointerOver;
  39056. },
  39057. enumerable: true,
  39058. configurable: true
  39059. });
  39060. Object.defineProperty(PrimitivePointerInfo, "PointerEnter", {
  39061. /**
  39062. * This event type is raised when a pointing device is moved into the hit test boundaries of a primitive or one of its descendants.
  39063. * Bubbles: no
  39064. */
  39065. get: function () {
  39066. return PrimitivePointerInfo._pointerEnter;
  39067. },
  39068. enumerable: true,
  39069. configurable: true
  39070. });
  39071. Object.defineProperty(PrimitivePointerInfo, "PointerDown", {
  39072. /**
  39073. * This event type is raised when a pointer enters the active button state (non-zero value in the buttons property). For mouse it's when the device transitions from no buttons depressed to at least one button depressed. For touch/pen this is when a physical contact is made.
  39074. * Bubbles: yes
  39075. */
  39076. get: function () {
  39077. return PrimitivePointerInfo._pointerDown;
  39078. },
  39079. enumerable: true,
  39080. configurable: true
  39081. });
  39082. Object.defineProperty(PrimitivePointerInfo, "PointerMouseWheel", {
  39083. /**
  39084. * This event type is raised when the pointer is a mouse and it's wheel is rolling
  39085. * Bubbles: yes
  39086. */
  39087. get: function () {
  39088. return PrimitivePointerInfo._pointerMouseWheel;
  39089. },
  39090. enumerable: true,
  39091. configurable: true
  39092. });
  39093. Object.defineProperty(PrimitivePointerInfo, "PointerMove", {
  39094. /**
  39095. * This event type is raised when a pointer change coordinates or when a pointer changes button state, pressure, tilt, or contact geometry and the circumstances produce no other pointers events.
  39096. * Bubbles: yes
  39097. */
  39098. get: function () {
  39099. return PrimitivePointerInfo._pointerMove;
  39100. },
  39101. enumerable: true,
  39102. configurable: true
  39103. });
  39104. Object.defineProperty(PrimitivePointerInfo, "PointerUp", {
  39105. /**
  39106. * This event type is raised when the pointer leaves the active buttons states (zero value in the buttons property). For mouse, this is when the device transitions from at least one button depressed to no buttons depressed. For touch/pen, this is when physical contact is removed.
  39107. * Bubbles: yes
  39108. */
  39109. get: function () {
  39110. return PrimitivePointerInfo._pointerUp;
  39111. },
  39112. enumerable: true,
  39113. configurable: true
  39114. });
  39115. Object.defineProperty(PrimitivePointerInfo, "PointerOut", {
  39116. /**
  39117. * This event type is raised when a pointing device is moved out of the hit test the boundaries of a primitive.
  39118. * Bubbles: yes
  39119. */
  39120. get: function () {
  39121. return PrimitivePointerInfo._pointerOut;
  39122. },
  39123. enumerable: true,
  39124. configurable: true
  39125. });
  39126. Object.defineProperty(PrimitivePointerInfo, "PointerLeave", {
  39127. /**
  39128. * This event type is raised when a pointing device is moved out of the hit test boundaries of a primitive and all its descendants.
  39129. * Bubbles: no
  39130. */
  39131. get: function () {
  39132. return PrimitivePointerInfo._pointerLeave;
  39133. },
  39134. enumerable: true,
  39135. configurable: true
  39136. });
  39137. Object.defineProperty(PrimitivePointerInfo, "PointerGotCapture", {
  39138. /**
  39139. * This event type is raised when a primitive receives the pointer capture. This event is fired at the element that is receiving pointer capture. Subsequent events for that pointer will be fired at this element.
  39140. * Bubbles: yes
  39141. */
  39142. get: function () {
  39143. return PrimitivePointerInfo._pointerGotCapture;
  39144. },
  39145. enumerable: true,
  39146. configurable: true
  39147. });
  39148. Object.defineProperty(PrimitivePointerInfo, "PointerLostCapture", {
  39149. /**
  39150. * This event type is raised after pointer capture is released for a pointer.
  39151. * Bubbles: yes
  39152. */
  39153. get: function () {
  39154. return PrimitivePointerInfo._pointerLostCapture;
  39155. },
  39156. enumerable: true,
  39157. configurable: true
  39158. });
  39159. Object.defineProperty(PrimitivePointerInfo, "MouseWheelPrecision", {
  39160. get: function () {
  39161. return PrimitivePointerInfo._mouseWheelPrecision;
  39162. },
  39163. enumerable: true,
  39164. configurable: true
  39165. });
  39166. PrimitivePointerInfo.prototype.updateRelatedTarget = function (prim, primPointerPos) {
  39167. this.relatedTarget = prim;
  39168. this.relatedTargetPointerPos = primPointerPos;
  39169. };
  39170. PrimitivePointerInfo.getEventTypeName = function (mask) {
  39171. switch (mask) {
  39172. case PrimitivePointerInfo.PointerOver: return "PointerOver";
  39173. case PrimitivePointerInfo.PointerEnter: return "PointerEnter";
  39174. case PrimitivePointerInfo.PointerDown: return "PointerDown";
  39175. case PrimitivePointerInfo.PointerMouseWheel: return "PointerMouseWheel";
  39176. case PrimitivePointerInfo.PointerMove: return "PointerMove";
  39177. case PrimitivePointerInfo.PointerUp: return "PointerUp";
  39178. case PrimitivePointerInfo.PointerOut: return "PointerOut";
  39179. case PrimitivePointerInfo.PointerLeave: return "PointerLeave";
  39180. case PrimitivePointerInfo.PointerGotCapture: return "PointerGotCapture";
  39181. case PrimitivePointerInfo.PointerLostCapture: return "PointerLostCapture";
  39182. }
  39183. };
  39184. PrimitivePointerInfo._pointerOver = 0x0001;
  39185. PrimitivePointerInfo._pointerEnter = 0x0002;
  39186. PrimitivePointerInfo._pointerDown = 0x0004;
  39187. PrimitivePointerInfo._pointerMouseWheel = 0x0008;
  39188. PrimitivePointerInfo._pointerMove = 0x0010;
  39189. PrimitivePointerInfo._pointerUp = 0x0020;
  39190. PrimitivePointerInfo._pointerOut = 0x0040;
  39191. PrimitivePointerInfo._pointerLeave = 0x0080;
  39192. PrimitivePointerInfo._pointerGotCapture = 0x0100;
  39193. PrimitivePointerInfo._pointerLostCapture = 0x0200;
  39194. PrimitivePointerInfo._mouseWheelPrecision = 3.0;
  39195. return PrimitivePointerInfo;
  39196. }());
  39197. BABYLON.PrimitivePointerInfo = PrimitivePointerInfo;
  39198. /**
  39199. * Defines the horizontal and vertical alignment information for a Primitive.
  39200. */
  39201. var PrimitiveAlignment = (function () {
  39202. function PrimitiveAlignment(changeCallback) {
  39203. this._changedCallback = changeCallback;
  39204. this._horizontal = PrimitiveAlignment.AlignLeft;
  39205. this._vertical = PrimitiveAlignment.AlignBottom;
  39206. }
  39207. Object.defineProperty(PrimitiveAlignment, "AlignLeft", {
  39208. /**
  39209. * Alignment is made relative to the left edge of the Primitive. Valid for horizontal alignment only.
  39210. */
  39211. get: function () { return PrimitiveAlignment._AlignLeft; },
  39212. enumerable: true,
  39213. configurable: true
  39214. });
  39215. Object.defineProperty(PrimitiveAlignment, "AlignTop", {
  39216. /**
  39217. * Alignment is made relative to the top edge of the Primitive. Valid for vertical alignment only.
  39218. */
  39219. get: function () { return PrimitiveAlignment._AlignTop; },
  39220. enumerable: true,
  39221. configurable: true
  39222. });
  39223. Object.defineProperty(PrimitiveAlignment, "AlignRight", {
  39224. /**
  39225. * Alignment is made relative to the right edge of the Primitive. Valid for horizontal alignment only.
  39226. */
  39227. get: function () { return PrimitiveAlignment._AlignRight; },
  39228. enumerable: true,
  39229. configurable: true
  39230. });
  39231. Object.defineProperty(PrimitiveAlignment, "AlignBottom", {
  39232. /**
  39233. * Alignment is made relative to the bottom edge of the Primitive. Valid for vertical alignment only.
  39234. */
  39235. get: function () { return PrimitiveAlignment._AlignBottom; },
  39236. enumerable: true,
  39237. configurable: true
  39238. });
  39239. Object.defineProperty(PrimitiveAlignment, "AlignCenter", {
  39240. /**
  39241. * Alignment is made to center the content from equal distance to the opposite edges of the Primitive
  39242. */
  39243. get: function () { return PrimitiveAlignment._AlignCenter; },
  39244. enumerable: true,
  39245. configurable: true
  39246. });
  39247. Object.defineProperty(PrimitiveAlignment, "AlignStretch", {
  39248. /**
  39249. * The content is stretched toward the opposite edges of the Primitive
  39250. */
  39251. get: function () { return PrimitiveAlignment._AlignStretch; },
  39252. enumerable: true,
  39253. configurable: true
  39254. });
  39255. Object.defineProperty(PrimitiveAlignment.prototype, "horizontal", {
  39256. /**
  39257. * Get/set the horizontal alignment. Use one of the AlignXXX static properties of this class
  39258. */
  39259. get: function () {
  39260. return this._horizontal;
  39261. },
  39262. set: function (value) {
  39263. if (this._horizontal === value) {
  39264. return;
  39265. }
  39266. this._horizontal = value;
  39267. this._changedCallback();
  39268. },
  39269. enumerable: true,
  39270. configurable: true
  39271. });
  39272. Object.defineProperty(PrimitiveAlignment.prototype, "vertical", {
  39273. /**
  39274. * Get/set the vertical alignment. Use one of the AlignXXX static properties of this class
  39275. */
  39276. get: function () {
  39277. return this._vertical;
  39278. },
  39279. set: function (value) {
  39280. if (this._vertical === value) {
  39281. return;
  39282. }
  39283. this._vertical = value;
  39284. this._changedCallback();
  39285. },
  39286. enumerable: true,
  39287. configurable: true
  39288. });
  39289. /**
  39290. * Set the horizontal alignment from a string value.
  39291. * @param text can be either: 'left','right','center','stretch'
  39292. */
  39293. PrimitiveAlignment.prototype.setHorizontal = function (text) {
  39294. var v = text.trim().toLocaleLowerCase();
  39295. switch (v) {
  39296. case "left":
  39297. this.horizontal = PrimitiveAlignment.AlignLeft;
  39298. return;
  39299. case "right":
  39300. this.horizontal = PrimitiveAlignment.AlignRight;
  39301. return;
  39302. case "center":
  39303. this.horizontal = PrimitiveAlignment.AlignCenter;
  39304. return;
  39305. case "stretch":
  39306. this.horizontal = PrimitiveAlignment.AlignStretch;
  39307. return;
  39308. }
  39309. };
  39310. /**
  39311. * Set the vertical alignment from a string value.
  39312. * @param text can be either: 'top','bottom','center','stretch'
  39313. */
  39314. PrimitiveAlignment.prototype.setVertical = function (text) {
  39315. var v = text.trim().toLocaleLowerCase();
  39316. switch (v) {
  39317. case "top":
  39318. this.vertical = PrimitiveAlignment.AlignTop;
  39319. return;
  39320. case "bottom":
  39321. this.vertical = PrimitiveAlignment.AlignBottom;
  39322. return;
  39323. case "center":
  39324. this.vertical = PrimitiveAlignment.AlignCenter;
  39325. return;
  39326. case "stretch":
  39327. this.vertical = PrimitiveAlignment.AlignStretch;
  39328. return;
  39329. }
  39330. };
  39331. /**
  39332. * Set the horizontal and or vertical alignments from a string value.
  39333. * @param text can be: [<h:|horizontal:><left|right|center|stretch>], [<v:|vertical:><top|bottom|center|stretch>]
  39334. */
  39335. PrimitiveAlignment.prototype.fromString = function (value) {
  39336. var m = value.trim().split(",");
  39337. for (var _i = 0, m_1 = m; _i < m_1.length; _i++) {
  39338. var v = m_1[_i];
  39339. v = v.toLocaleLowerCase().trim();
  39340. // Horizontal
  39341. var i = v.indexOf("h:");
  39342. if (i === -1) {
  39343. i = v.indexOf("horizontal:");
  39344. }
  39345. if (i !== -1) {
  39346. v = v.substr(v.indexOf(":") + 1);
  39347. this.setHorizontal(v);
  39348. continue;
  39349. }
  39350. // Vertical
  39351. i = v.indexOf("v:");
  39352. if (i === -1) {
  39353. i = v.indexOf("vertical:");
  39354. }
  39355. if (i !== -1) {
  39356. v = v.substr(v.indexOf(":") + 1);
  39357. this.setVertical(v);
  39358. continue;
  39359. }
  39360. }
  39361. };
  39362. PrimitiveAlignment._AlignLeft = 1;
  39363. PrimitiveAlignment._AlignTop = 1; // Same as left
  39364. PrimitiveAlignment._AlignRight = 2;
  39365. PrimitiveAlignment._AlignBottom = 2; // Same as right
  39366. PrimitiveAlignment._AlignCenter = 3;
  39367. PrimitiveAlignment._AlignStretch = 4;
  39368. return PrimitiveAlignment;
  39369. }());
  39370. BABYLON.PrimitiveAlignment = PrimitiveAlignment;
  39371. /**
  39372. * Stores information about a Primitive that was intersected
  39373. */
  39374. var PrimitiveIntersectedInfo = (function () {
  39375. function PrimitiveIntersectedInfo(prim, intersectionLocation) {
  39376. this.prim = prim;
  39377. this.intersectionLocation = intersectionLocation;
  39378. }
  39379. return PrimitiveIntersectedInfo;
  39380. }());
  39381. BABYLON.PrimitiveIntersectedInfo = PrimitiveIntersectedInfo;
  39382. /**
  39383. * Define a thickness toward every edges of a Primitive to allow margin and padding.
  39384. * The thickness can be expressed as pixels, percentages, inherit the value of the parent primitive or be auto.
  39385. */
  39386. var PrimitiveThickness = (function () {
  39387. function PrimitiveThickness(parentAccess, changedCallback) {
  39388. this._parentAccess = parentAccess;
  39389. this._changedCallback = changedCallback;
  39390. this._pixels = new Array(4);
  39391. this._percentages = new Array(4);
  39392. this._setType(0, PrimitiveThickness.Auto);
  39393. this._setType(1, PrimitiveThickness.Auto);
  39394. this._setType(2, PrimitiveThickness.Auto);
  39395. this._setType(3, PrimitiveThickness.Auto);
  39396. this._pixels[0] = 0;
  39397. this._pixels[1] = 0;
  39398. this._pixels[2] = 0;
  39399. this._pixels[3] = 0;
  39400. }
  39401. /**
  39402. * Set the thickness from a string value
  39403. * @param thickness format is "top: <value>, left:<value>, right:<value>, bottom:<value>" or "<value>" (same for all edges) each are optional, auto will be set if it's omitted.
  39404. * Values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39405. */
  39406. PrimitiveThickness.prototype.fromString = function (thickness) {
  39407. this._clear();
  39408. var m = thickness.trim().split(",");
  39409. // Special case, one value to apply to all edges
  39410. if (m.length === 1 && thickness.indexOf(":") === -1) {
  39411. this._setStringValue(m[0], 0, false);
  39412. this._setStringValue(m[0], 1, false);
  39413. this._setStringValue(m[0], 2, false);
  39414. this._setStringValue(m[0], 3, false);
  39415. this._changedCallback();
  39416. return;
  39417. }
  39418. var res = false;
  39419. for (var _i = 0, m_2 = m; _i < m_2.length; _i++) {
  39420. var cm = m_2[_i];
  39421. res = this._extractString(cm, false) || res;
  39422. }
  39423. if (!res) {
  39424. throw new Error("Can't parse the string to create a PrimitiveMargin object, format must be: 'top: <value>, left:<value>, right:<value>, bottom:<value>");
  39425. }
  39426. // Check the margin that weren't set and set them in auto
  39427. if ((this._flags & 0x000F) === 0)
  39428. this._flags |= PrimitiveThickness.Pixel << 0;
  39429. if ((this._flags & 0x00F0) === 0)
  39430. this._flags |= PrimitiveThickness.Pixel << 4;
  39431. if ((this._flags & 0x0F00) === 0)
  39432. this._flags |= PrimitiveThickness.Pixel << 8;
  39433. if ((this._flags & 0xF000) === 0)
  39434. this._flags |= PrimitiveThickness.Pixel << 12;
  39435. this._changedCallback();
  39436. };
  39437. /**
  39438. * Set the thickness from multiple string
  39439. * Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39440. * @param top the top thickness to set
  39441. * @param left the left thickness to set
  39442. * @param right the right thickness to set
  39443. * @param bottom the bottom thickness to set
  39444. */
  39445. PrimitiveThickness.prototype.fromStrings = function (top, left, right, bottom) {
  39446. this._clear();
  39447. this._setStringValue(top, 0, false);
  39448. this._setStringValue(left, 1, false);
  39449. this._setStringValue(right, 2, false);
  39450. this._setStringValue(bottom, 3, false);
  39451. this._changedCallback();
  39452. return this;
  39453. };
  39454. /**
  39455. * Set the thickness from pixel values
  39456. * @param top the top thickness in pixels to set
  39457. * @param left the left thickness in pixels to set
  39458. * @param right the right thickness in pixels to set
  39459. * @param bottom the bottom thickness in pixels to set
  39460. */
  39461. PrimitiveThickness.prototype.fromPixels = function (top, left, right, bottom) {
  39462. this._clear();
  39463. this._pixels[0] = top;
  39464. this._pixels[1] = left;
  39465. this._pixels[2] = right;
  39466. this._pixels[3] = bottom;
  39467. this._changedCallback();
  39468. return this;
  39469. };
  39470. /**
  39471. * Apply the same pixel value to all edges
  39472. * @param margin the value to set, in pixels.
  39473. */
  39474. PrimitiveThickness.prototype.fromUniformPixels = function (margin) {
  39475. this._clear();
  39476. this._pixels[0] = margin;
  39477. this._pixels[1] = margin;
  39478. this._pixels[2] = margin;
  39479. this._pixels[3] = margin;
  39480. this._changedCallback();
  39481. return this;
  39482. };
  39483. /**
  39484. * Set all edges in auto
  39485. */
  39486. PrimitiveThickness.prototype.auto = function () {
  39487. this._clear();
  39488. this._flags = (PrimitiveThickness.Auto << 0) | (PrimitiveThickness.Auto << 4) | (PrimitiveThickness.Auto << 8) | (PrimitiveThickness.Auto << 12);
  39489. this._pixels[0] = 0;
  39490. this._pixels[1] = 0;
  39491. this._pixels[2] = 0;
  39492. this._pixels[3] = 0;
  39493. this._changedCallback();
  39494. return this;
  39495. };
  39496. PrimitiveThickness.prototype._clear = function () {
  39497. this._flags = 0;
  39498. this._pixels[0] = 0;
  39499. this._pixels[1] = 0;
  39500. this._pixels[2] = 0;
  39501. this._pixels[3] = 0;
  39502. this._percentages[0] = null;
  39503. this._percentages[1] = null;
  39504. this._percentages[2] = null;
  39505. this._percentages[3] = null;
  39506. };
  39507. PrimitiveThickness.prototype._extractString = function (value, emitChanged) {
  39508. var v = value.trim().toLocaleLowerCase();
  39509. if (v.indexOf("top:") === 0) {
  39510. v = v.substr(4).trim();
  39511. return this._setStringValue(v, 0, emitChanged);
  39512. }
  39513. if (v.indexOf("left:") === 0) {
  39514. v = v.substr(5).trim();
  39515. return this._setStringValue(v, 1, emitChanged);
  39516. }
  39517. if (v.indexOf("right:") === 0) {
  39518. v = v.substr(6).trim();
  39519. return this._setStringValue(v, 2, emitChanged);
  39520. }
  39521. if (v.indexOf("bottom:") === 0) {
  39522. v = v.substr(7).trim();
  39523. return this._setStringValue(v, 3, emitChanged);
  39524. }
  39525. return false;
  39526. };
  39527. PrimitiveThickness.prototype._setStringValue = function (value, index, emitChanged) {
  39528. // Check for auto
  39529. var v = value.trim().toLocaleLowerCase();
  39530. if (v === "auto") {
  39531. if (this._isType(index, PrimitiveThickness.Auto)) {
  39532. return true;
  39533. }
  39534. this._setType(index, PrimitiveThickness.Auto);
  39535. this._pixels[index] = 0;
  39536. if (emitChanged) {
  39537. this._changedCallback();
  39538. }
  39539. }
  39540. else if (v === "inherit") {
  39541. if (this._isType(index, PrimitiveThickness.Inherit)) {
  39542. return true;
  39543. }
  39544. this._setType(index, PrimitiveThickness.Inherit);
  39545. this._pixels[index] = null;
  39546. if (emitChanged) {
  39547. this._changedCallback();
  39548. }
  39549. }
  39550. else {
  39551. var pI = v.indexOf("%");
  39552. // Check for percentage
  39553. if (pI !== -1) {
  39554. var n_1 = v.substr(0, pI);
  39555. var number_1 = Math.round(Number(n_1)) / 100; // Normalize the percentage to [0;1] with a 0.01 precision
  39556. if (this._isType(index, PrimitiveThickness.Percentage) && (this._percentages[index] === number_1)) {
  39557. return true;
  39558. }
  39559. this._setType(index, PrimitiveThickness.Percentage);
  39560. if (isNaN(number_1)) {
  39561. return false;
  39562. }
  39563. this._percentages[index] = number_1;
  39564. if (emitChanged) {
  39565. this._changedCallback();
  39566. }
  39567. return true;
  39568. }
  39569. // Check for pixel
  39570. var n = void 0;
  39571. pI = v.indexOf("px");
  39572. if (pI !== -1) {
  39573. n = v.substr(0, pI).trim();
  39574. }
  39575. else {
  39576. n = v;
  39577. }
  39578. var number = Number(n);
  39579. if (this._isType(index, PrimitiveThickness.Pixel) && (this._pixels[index] === number)) {
  39580. return true;
  39581. }
  39582. if (isNaN(number)) {
  39583. return false;
  39584. }
  39585. this._pixels[index] = number;
  39586. this._setType(index, PrimitiveThickness.Pixel);
  39587. if (emitChanged) {
  39588. this._changedCallback();
  39589. }
  39590. return true;
  39591. }
  39592. };
  39593. PrimitiveThickness.prototype._setPixels = function (value, index, emitChanged) {
  39594. // Round the value because, well, it's the thing to do! Otherwise we'll have sub-pixel stuff, and the no change comparison just below will almost never work for PrimitiveThickness values inside a hierarchy of Primitives
  39595. value = Math.round(value);
  39596. if (this._isType(index, PrimitiveThickness.Pixel) && this._pixels[index] === value) {
  39597. return;
  39598. }
  39599. this._setType(index, PrimitiveThickness.Pixel);
  39600. this._pixels[index] = value;
  39601. if (emitChanged) {
  39602. this._changedCallback();
  39603. }
  39604. };
  39605. PrimitiveThickness.prototype._setPercentage = function (value, index, emitChanged) {
  39606. // Clip Value to bounds
  39607. value = Math.min(1, value);
  39608. value = Math.max(0, value);
  39609. value = Math.round(value * 100) / 100; // 0.01 precision
  39610. if (this._isType(index, PrimitiveThickness.Percentage) && this._percentages[index] === value) {
  39611. return;
  39612. }
  39613. this._setType(index, PrimitiveThickness.Percentage);
  39614. this._percentages[index] = value;
  39615. if (emitChanged) {
  39616. this._changedCallback();
  39617. }
  39618. };
  39619. PrimitiveThickness.prototype._getStringValue = function (index) {
  39620. var f = (this._flags >> (index * 4)) & 0xF;
  39621. switch (f) {
  39622. case PrimitiveThickness.Auto:
  39623. return "auto";
  39624. case PrimitiveThickness.Pixel:
  39625. return this._pixels[index] + "px";
  39626. case PrimitiveThickness.Percentage:
  39627. return this._percentages[index] * 100 + "%";
  39628. case PrimitiveThickness.Inherit:
  39629. return "inherit";
  39630. }
  39631. return "";
  39632. };
  39633. PrimitiveThickness.prototype._isType = function (index, type) {
  39634. var f = (this._flags >> (index * 4)) & 0xF;
  39635. return f === type;
  39636. };
  39637. PrimitiveThickness.prototype._getType = function (index, processInherit) {
  39638. var t = (this._flags >> (index * 4)) & 0xF;
  39639. if (processInherit && (t === PrimitiveThickness.Inherit)) {
  39640. var p = this._parentAccess();
  39641. if (p) {
  39642. return p._getType(index, true);
  39643. }
  39644. return PrimitiveThickness.Auto;
  39645. }
  39646. return t;
  39647. };
  39648. PrimitiveThickness.prototype._setType = function (index, type) {
  39649. this._flags &= ~(0xF << (index * 4));
  39650. this._flags |= type << (index * 4);
  39651. };
  39652. PrimitiveThickness.prototype.setTop = function (value) {
  39653. if (typeof value === "string") {
  39654. this._setStringValue(value, 0, true);
  39655. }
  39656. else {
  39657. this.topPixels = value;
  39658. }
  39659. };
  39660. PrimitiveThickness.prototype.setLeft = function (value) {
  39661. if (typeof value === "string") {
  39662. this._setStringValue(value, 1, true);
  39663. }
  39664. else {
  39665. this.leftPixels = value;
  39666. }
  39667. };
  39668. PrimitiveThickness.prototype.setRight = function (value) {
  39669. if (typeof value === "string") {
  39670. this._setStringValue(value, 2, true);
  39671. }
  39672. else {
  39673. this.rightPixels = value;
  39674. }
  39675. };
  39676. PrimitiveThickness.prototype.setBottom = function (value) {
  39677. if (typeof value === "string") {
  39678. this._setStringValue(value, 3, true);
  39679. }
  39680. else {
  39681. this.bottomPixels = value;
  39682. }
  39683. };
  39684. Object.defineProperty(PrimitiveThickness.prototype, "top", {
  39685. /**
  39686. * Get/set the top thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39687. */
  39688. get: function () {
  39689. return this._getStringValue(0);
  39690. },
  39691. set: function (value) {
  39692. this._setStringValue(value, 0, true);
  39693. },
  39694. enumerable: true,
  39695. configurable: true
  39696. });
  39697. Object.defineProperty(PrimitiveThickness.prototype, "left", {
  39698. /**
  39699. * Get/set the left thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39700. */
  39701. get: function () {
  39702. return this._getStringValue(1);
  39703. },
  39704. set: function (value) {
  39705. this._setStringValue(value, 1, true);
  39706. },
  39707. enumerable: true,
  39708. configurable: true
  39709. });
  39710. Object.defineProperty(PrimitiveThickness.prototype, "right", {
  39711. /**
  39712. * Get/set the right thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39713. */
  39714. get: function () {
  39715. return this._getStringValue(2);
  39716. },
  39717. set: function (value) {
  39718. this._setStringValue(value, 2, true);
  39719. },
  39720. enumerable: true,
  39721. configurable: true
  39722. });
  39723. Object.defineProperty(PrimitiveThickness.prototype, "bottom", {
  39724. /**
  39725. * Get/set the bottom thickness. Possible values are: 'auto', 'inherit', 'XX%' for percentage, 'XXpx' or 'XX' for pixels.
  39726. */
  39727. get: function () {
  39728. return this._getStringValue(3);
  39729. },
  39730. set: function (value) {
  39731. this._setStringValue(value, 3, true);
  39732. },
  39733. enumerable: true,
  39734. configurable: true
  39735. });
  39736. Object.defineProperty(PrimitiveThickness.prototype, "topPixels", {
  39737. /**
  39738. * Get/set the top thickness in pixel.
  39739. */
  39740. get: function () {
  39741. return this._pixels[0];
  39742. },
  39743. set: function (value) {
  39744. this._setPixels(value, 0, true);
  39745. },
  39746. enumerable: true,
  39747. configurable: true
  39748. });
  39749. Object.defineProperty(PrimitiveThickness.prototype, "leftPixels", {
  39750. /**
  39751. * Get/set the left thickness in pixel.
  39752. */
  39753. get: function () {
  39754. return this._pixels[1];
  39755. },
  39756. set: function (value) {
  39757. this._setPixels(value, 1, true);
  39758. },
  39759. enumerable: true,
  39760. configurable: true
  39761. });
  39762. Object.defineProperty(PrimitiveThickness.prototype, "rightPixels", {
  39763. /**
  39764. * Get/set the right thickness in pixel.
  39765. */
  39766. get: function () {
  39767. return this._pixels[2];
  39768. },
  39769. set: function (value) {
  39770. this._setPixels(value, 2, true);
  39771. },
  39772. enumerable: true,
  39773. configurable: true
  39774. });
  39775. Object.defineProperty(PrimitiveThickness.prototype, "bottomPixels", {
  39776. /**
  39777. * Get/set the bottom thickness in pixel.
  39778. */
  39779. get: function () {
  39780. return this._pixels[3];
  39781. },
  39782. set: function (value) {
  39783. this._setPixels(value, 3, true);
  39784. },
  39785. enumerable: true,
  39786. configurable: true
  39787. });
  39788. Object.defineProperty(PrimitiveThickness.prototype, "topPercentage", {
  39789. /**
  39790. * Get/set the top thickness in percentage.
  39791. * The get will return a valid value only if the edge type is percentage.
  39792. * The Set will change the edge mode if needed
  39793. */
  39794. get: function () {
  39795. return this._percentages[0];
  39796. },
  39797. set: function (value) {
  39798. this._setPercentage(value, 0, true);
  39799. },
  39800. enumerable: true,
  39801. configurable: true
  39802. });
  39803. Object.defineProperty(PrimitiveThickness.prototype, "leftPercentage", {
  39804. /**
  39805. * Get/set the left thickness in percentage.
  39806. * The get will return a valid value only if the edge mode is percentage.
  39807. * The Set will change the edge mode if needed
  39808. */
  39809. get: function () {
  39810. return this._percentages[1];
  39811. },
  39812. set: function (value) {
  39813. this._setPercentage(value, 1, true);
  39814. },
  39815. enumerable: true,
  39816. configurable: true
  39817. });
  39818. Object.defineProperty(PrimitiveThickness.prototype, "rightPercentage", {
  39819. /**
  39820. * Get/set the right thickness in percentage.
  39821. * The get will return a valid value only if the edge mode is percentage.
  39822. * The Set will change the edge mode if needed
  39823. */
  39824. get: function () {
  39825. return this._percentages[2];
  39826. },
  39827. set: function (value) {
  39828. this._setPercentage(value, 2, true);
  39829. },
  39830. enumerable: true,
  39831. configurable: true
  39832. });
  39833. Object.defineProperty(PrimitiveThickness.prototype, "bottomPercentage", {
  39834. /**
  39835. * Get/set the bottom thickness in percentage.
  39836. * The get will return a valid value only if the edge mode is percentage.
  39837. * The Set will change the edge mode if needed
  39838. */
  39839. get: function () {
  39840. return this._percentages[3];
  39841. },
  39842. set: function (value) {
  39843. this._setPercentage(value, 3, true);
  39844. },
  39845. enumerable: true,
  39846. configurable: true
  39847. });
  39848. Object.defineProperty(PrimitiveThickness.prototype, "topMode", {
  39849. /**
  39850. * Get/set the top mode. The setter shouldn't be used, other setters with value should be preferred
  39851. */
  39852. get: function () {
  39853. return this._getType(0, false);
  39854. },
  39855. set: function (mode) {
  39856. this._setType(0, mode);
  39857. },
  39858. enumerable: true,
  39859. configurable: true
  39860. });
  39861. Object.defineProperty(PrimitiveThickness.prototype, "leftMode", {
  39862. /**
  39863. * Get/set the left mode. The setter shouldn't be used, other setters with value should be preferred
  39864. */
  39865. get: function () {
  39866. return this._getType(1, false);
  39867. },
  39868. set: function (mode) {
  39869. this._setType(1, mode);
  39870. },
  39871. enumerable: true,
  39872. configurable: true
  39873. });
  39874. Object.defineProperty(PrimitiveThickness.prototype, "rightMode", {
  39875. /**
  39876. * Get/set the right mode. The setter shouldn't be used, other setters with value should be preferred
  39877. */
  39878. get: function () {
  39879. return this._getType(2, false);
  39880. },
  39881. set: function (mode) {
  39882. this._setType(2, mode);
  39883. },
  39884. enumerable: true,
  39885. configurable: true
  39886. });
  39887. Object.defineProperty(PrimitiveThickness.prototype, "bottomMode", {
  39888. /**
  39889. * Get/set the bottom mode. The setter shouldn't be used, other setters with value should be preferred
  39890. */
  39891. get: function () {
  39892. return this._getType(3, false);
  39893. },
  39894. set: function (mode) {
  39895. this._setType(3, mode);
  39896. },
  39897. enumerable: true,
  39898. configurable: true
  39899. });
  39900. PrimitiveThickness.prototype._computePixels = function (index, sourceArea, emitChanged) {
  39901. var type = this._getType(index, false);
  39902. if (type === PrimitiveThickness.Inherit) {
  39903. this._parentAccess()._computePixels(index, sourceArea, emitChanged);
  39904. return;
  39905. }
  39906. if (type !== PrimitiveThickness.Percentage) {
  39907. return;
  39908. }
  39909. var pixels = ((index === 0 || index === 3) ? sourceArea.height : sourceArea.width) * this._percentages[index];
  39910. this._pixels[index] = pixels;
  39911. if (emitChanged) {
  39912. this._changedCallback();
  39913. }
  39914. };
  39915. /**
  39916. * Compute the positioning/size of an area considering the thickness of this object and a given alignment
  39917. * @param sourceArea the source area
  39918. * @param contentSize the content size to position/resize
  39919. * @param alignment the alignment setting
  39920. * @param dstOffset the position of the content
  39921. * @param dstArea the new size of the content
  39922. */
  39923. PrimitiveThickness.prototype.computeWithAlignment = function (sourceArea, contentSize, alignment, dstOffset, dstArea) {
  39924. // Fetch some data
  39925. var topType = this._getType(0, true);
  39926. var leftType = this._getType(1, true);
  39927. var rightType = this._getType(2, true);
  39928. var bottomType = this._getType(3, true);
  39929. var hasWidth = contentSize && (contentSize.width != null);
  39930. var hasHeight = contentSize && (contentSize.height != null);
  39931. var width = hasWidth ? contentSize.width : 0;
  39932. var height = hasHeight ? contentSize.height : 0;
  39933. var isTopAuto = topType === PrimitiveThickness.Auto;
  39934. var isLeftAuto = leftType === PrimitiveThickness.Auto;
  39935. var isRightAuto = rightType === PrimitiveThickness.Auto;
  39936. var isBottomAuto = bottomType === PrimitiveThickness.Auto;
  39937. switch (alignment.horizontal) {
  39938. case PrimitiveAlignment.AlignLeft:
  39939. {
  39940. if (isLeftAuto) {
  39941. dstOffset.x = 0;
  39942. }
  39943. else {
  39944. this._computePixels(1, sourceArea, true);
  39945. dstOffset.x = this.leftPixels;
  39946. }
  39947. dstArea.width = width;
  39948. break;
  39949. }
  39950. case PrimitiveAlignment.AlignRight:
  39951. {
  39952. if (isRightAuto) {
  39953. dstOffset.x = Math.round(sourceArea.width - width);
  39954. }
  39955. else {
  39956. this._computePixels(2, sourceArea, true);
  39957. dstOffset.x = Math.round(sourceArea.width - (width + this.rightPixels));
  39958. }
  39959. dstArea.width = width;
  39960. break;
  39961. }
  39962. case PrimitiveAlignment.AlignStretch:
  39963. {
  39964. if (isLeftAuto) {
  39965. dstOffset.x = 0;
  39966. }
  39967. else {
  39968. this._computePixels(1, sourceArea, true);
  39969. dstOffset.x = this.leftPixels;
  39970. }
  39971. var right = 0;
  39972. if (!isRightAuto) {
  39973. this._computePixels(2, sourceArea, true);
  39974. right = this.rightPixels;
  39975. }
  39976. dstArea.width = sourceArea.width - (dstOffset.x + right);
  39977. break;
  39978. }
  39979. case PrimitiveAlignment.AlignCenter:
  39980. {
  39981. if (!isLeftAuto) {
  39982. this._computePixels(1, sourceArea, true);
  39983. }
  39984. if (!isRightAuto) {
  39985. this._computePixels(2, sourceArea, true);
  39986. }
  39987. var offset = (isLeftAuto ? 0 : this.leftPixels) - (isRightAuto ? 0 : this.rightPixels);
  39988. dstOffset.x = Math.round(((sourceArea.width - width) / 2) + offset);
  39989. dstArea.width = width;
  39990. break;
  39991. }
  39992. }
  39993. switch (alignment.vertical) {
  39994. case PrimitiveAlignment.AlignTop:
  39995. {
  39996. if (isTopAuto) {
  39997. dstOffset.y = sourceArea.height - height;
  39998. }
  39999. else {
  40000. this._computePixels(0, sourceArea, true);
  40001. dstOffset.y = Math.round(sourceArea.height - (height + this.topPixels));
  40002. }
  40003. dstArea.height = height;
  40004. break;
  40005. }
  40006. case PrimitiveAlignment.AlignBottom:
  40007. {
  40008. if (isBottomAuto) {
  40009. dstOffset.y = 0;
  40010. }
  40011. else {
  40012. this._computePixels(3, sourceArea, true);
  40013. dstOffset.y = this.bottomPixels;
  40014. }
  40015. dstArea.height = height;
  40016. break;
  40017. }
  40018. case PrimitiveAlignment.AlignStretch:
  40019. {
  40020. if (isBottomAuto) {
  40021. dstOffset.y = 0;
  40022. }
  40023. else {
  40024. this._computePixels(3, sourceArea, true);
  40025. dstOffset.y = this.bottomPixels;
  40026. }
  40027. var top_1 = 0;
  40028. if (!isTopAuto) {
  40029. this._computePixels(0, sourceArea, true);
  40030. top_1 = this.topPixels;
  40031. }
  40032. dstArea.height = sourceArea.height - (dstOffset.y + top_1);
  40033. break;
  40034. }
  40035. case PrimitiveAlignment.AlignCenter:
  40036. {
  40037. if (!isTopAuto) {
  40038. this._computePixels(0, sourceArea, true);
  40039. }
  40040. if (!isBottomAuto) {
  40041. this._computePixels(3, sourceArea, true);
  40042. }
  40043. var offset = (isBottomAuto ? 0 : this.bottomPixels) - (isTopAuto ? 0 : this.topPixels);
  40044. dstOffset.y = Math.round(((sourceArea.height - height) / 2) + offset);
  40045. dstArea.height = height;
  40046. break;
  40047. }
  40048. }
  40049. };
  40050. /**
  40051. * Compute an area and its position considering this thickness properties based on a given source area
  40052. * @param sourceArea the source area
  40053. * @param dstOffset the position of the resulting area
  40054. * @param dstArea the size of the resulting area
  40055. */
  40056. PrimitiveThickness.prototype.compute = function (sourceArea, dstOffset, dstArea) {
  40057. this._computePixels(0, sourceArea, true);
  40058. this._computePixels(1, sourceArea, true);
  40059. this._computePixels(2, sourceArea, true);
  40060. this._computePixels(3, sourceArea, true);
  40061. dstOffset.x = this.leftPixels;
  40062. dstArea.width = sourceArea.width - (dstOffset.x + this.rightPixels);
  40063. dstOffset.y = this.bottomPixels;
  40064. dstArea.height = sourceArea.height - (dstOffset.y + this.topPixels);
  40065. };
  40066. /**
  40067. * Compute an area considering this thickness properties based on a given source area
  40068. * @param sourceArea the source area
  40069. * @param result the resulting area
  40070. */
  40071. PrimitiveThickness.prototype.computeArea = function (sourceArea, result) {
  40072. this._computePixels(0, sourceArea, true);
  40073. this._computePixels(1, sourceArea, true);
  40074. this._computePixels(2, sourceArea, true);
  40075. this._computePixels(3, sourceArea, true);
  40076. result.width = this.leftPixels + sourceArea.width + this.rightPixels;
  40077. result.height = this.bottomPixels + sourceArea.height + this.topPixels;
  40078. };
  40079. PrimitiveThickness.prototype.enlarge = function (sourceArea, dstOffset, enlargedArea) {
  40080. this._computePixels(0, sourceArea, true);
  40081. this._computePixels(1, sourceArea, true);
  40082. this._computePixels(2, sourceArea, true);
  40083. this._computePixels(3, sourceArea, true);
  40084. dstOffset.x = this.leftPixels;
  40085. enlargedArea.width = sourceArea.width + (dstOffset.x + this.rightPixels);
  40086. dstOffset.y = this.bottomPixels;
  40087. enlargedArea.height = sourceArea.height + (dstOffset.y + this.topPixels);
  40088. };
  40089. PrimitiveThickness.Auto = 0x1;
  40090. PrimitiveThickness.Inherit = 0x2;
  40091. PrimitiveThickness.Percentage = 0x4;
  40092. PrimitiveThickness.Pixel = 0x8;
  40093. return PrimitiveThickness;
  40094. }());
  40095. BABYLON.PrimitiveThickness = PrimitiveThickness;
  40096. /**
  40097. * Main class used for the Primitive Intersection API
  40098. */
  40099. var IntersectInfo2D = (function () {
  40100. function IntersectInfo2D() {
  40101. this.findFirstOnly = false;
  40102. this.intersectHidden = false;
  40103. this.pickPosition = BABYLON.Vector2.Zero();
  40104. }
  40105. Object.defineProperty(IntersectInfo2D.prototype, "isIntersected", {
  40106. /**
  40107. * true if at least one primitive intersected during the test
  40108. */
  40109. get: function () {
  40110. return this.intersectedPrimitives && this.intersectedPrimitives.length > 0;
  40111. },
  40112. enumerable: true,
  40113. configurable: true
  40114. });
  40115. IntersectInfo2D.prototype.isPrimIntersected = function (prim) {
  40116. for (var _i = 0, _a = this.intersectedPrimitives; _i < _a.length; _i++) {
  40117. var cur = _a[_i];
  40118. if (cur.prim === prim) {
  40119. return cur.intersectionLocation;
  40120. }
  40121. }
  40122. return null;
  40123. };
  40124. // Internals, don't use
  40125. IntersectInfo2D.prototype._exit = function (firstLevel) {
  40126. if (firstLevel) {
  40127. this._globalPickPosition = null;
  40128. }
  40129. };
  40130. return IntersectInfo2D;
  40131. }());
  40132. BABYLON.IntersectInfo2D = IntersectInfo2D;
  40133. var Prim2DBase = (function (_super) {
  40134. __extends(Prim2DBase, _super);
  40135. function Prim2DBase(settings) {
  40136. // Avoid checking every time if the object exists
  40137. if (settings == null) {
  40138. settings = {};
  40139. }
  40140. // BASE CLASS CALL
  40141. _super.call(this);
  40142. // Fetch the owner, parent. There're many ways to do it and we can end up with nothing for both
  40143. var owner;
  40144. var parent;
  40145. if (Prim2DBase._isCanvasInit) {
  40146. owner = this;
  40147. parent = null;
  40148. this._canvasPreInit(settings);
  40149. }
  40150. else {
  40151. if (settings.parent != null) {
  40152. parent = settings.parent;
  40153. owner = settings.parent.owner;
  40154. if (!owner) {
  40155. throw new Error("Parent " + parent.id + " of " + settings.id + " doesn't have a valid owner!");
  40156. }
  40157. if (!(this instanceof BABYLON.Group2D) && !(this instanceof BABYLON.Sprite2D && settings.id != null && settings.id.indexOf("__cachedSpriteOfGroup__") === 0) && (owner.cachingStrategy === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) && (parent === owner)) {
  40158. throw new Error("Can't create a primitive with the canvas as direct parent when the caching strategy is TOPLEVELGROUPS. You need to create a Group below the canvas and use it as the parent for the primitive");
  40159. }
  40160. }
  40161. }
  40162. // Fields initialization
  40163. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40164. this._size = null; //Size.Zero();
  40165. this._scale = new BABYLON.Vector2(1, 1);
  40166. this._actualSize = null;
  40167. this._boundingSize = BABYLON.Size.Zero();
  40168. this._layoutArea = BABYLON.Size.Zero();
  40169. this._layoutAreaPos = BABYLON.Vector2.Zero();
  40170. this._marginOffset = BABYLON.Vector2.Zero();
  40171. this._paddingOffset = BABYLON.Vector2.Zero();
  40172. this._parentPaddingOffset = BABYLON.Vector2.Zero();
  40173. this._parentContentArea = BABYLON.Size.Zero();
  40174. this._lastAutoSizeArea = BABYLON.Size.Zero();
  40175. this._contentArea = new BABYLON.Size(null, null);
  40176. this._pointerEventObservable = new BABYLON.Observable();
  40177. this._boundingInfo = new BABYLON.BoundingInfo2D();
  40178. this._owner = owner;
  40179. this._parent = null;
  40180. this._margin = null;
  40181. this._padding = null;
  40182. this._marginAlignment = null;
  40183. this._id = settings.id;
  40184. this.propertyChanged = new BABYLON.Observable();
  40185. this._children = new Array();
  40186. this._localTransform = new BABYLON.Matrix();
  40187. this._globalTransform = null;
  40188. this._invGlobalTransform = null;
  40189. this._globalTransformProcessStep = 0;
  40190. this._globalTransformStep = 0;
  40191. this._renderGroup = null;
  40192. this._primLinearPosition = 0;
  40193. this._manualZOrder = null;
  40194. this._zOrder = 0;
  40195. this._zMax = 0;
  40196. this._firstZDirtyIndex = Prim2DBase._bigInt;
  40197. var isPickable = true;
  40198. var isContainer = true;
  40199. if (settings.isPickable !== undefined) {
  40200. isPickable = settings.isPickable;
  40201. }
  40202. if (settings.isContainer !== undefined) {
  40203. isContainer = settings.isContainer;
  40204. }
  40205. this._setFlags((isPickable ? BABYLON.SmartPropertyPrim.flagIsPickable : 0) | BABYLON.SmartPropertyPrim.flagBoundingInfoDirty | BABYLON.SmartPropertyPrim.flagActualOpacityDirty | (isContainer ? BABYLON.SmartPropertyPrim.flagIsContainer : 0));
  40206. if (settings.opacity != null) {
  40207. this._opacity = settings.opacity;
  40208. }
  40209. else {
  40210. this._opacity = 1;
  40211. }
  40212. this._updateRenderMode();
  40213. if (settings.childrenFlatZOrder) {
  40214. this._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  40215. }
  40216. // If the parent is given, initialize the hierarchy/owner related data
  40217. if (parent != null) {
  40218. parent.addChild(this);
  40219. this._hierarchyDepth = parent._hierarchyDepth + 1;
  40220. this._patchHierarchy(parent.owner);
  40221. }
  40222. // If it's a group, detect its own states
  40223. if (this.owner && this instanceof BABYLON.Group2D) {
  40224. var group = this;
  40225. group.detectGroupStates();
  40226. }
  40227. // Time to insert children if some are specified
  40228. if (settings.children != null) {
  40229. for (var _i = 0, _a = settings.children; _i < _a.length; _i++) {
  40230. var child = _a[_i];
  40231. this.addChild(child);
  40232. // Good time to patch the hierarchy, it won't go very far if there's no need to
  40233. if (this.owner != null) {
  40234. child._patchHierarchy(this.owner);
  40235. }
  40236. }
  40237. }
  40238. if (settings.zOrder != null) {
  40239. this.zOrder = settings.zOrder;
  40240. }
  40241. // Set the model related properties
  40242. if (settings.position != null) {
  40243. this.position = settings.position;
  40244. }
  40245. else if (settings.x != null || settings.y != null) {
  40246. this.position = new BABYLON.Vector2(settings.x || 0, settings.y || 0);
  40247. }
  40248. else {
  40249. this._position = null;
  40250. }
  40251. this.rotation = (settings.rotation == null) ? 0 : settings.rotation;
  40252. if (settings.scale != null) {
  40253. this.scale = settings.scale;
  40254. }
  40255. else {
  40256. if (settings.scaleX != null) {
  40257. this.scaleX = settings.scaleX;
  40258. }
  40259. if (settings.scaleY != null) {
  40260. this.scaleY = settings.scaleY;
  40261. }
  40262. }
  40263. this.levelVisible = (settings.isVisible == null) ? true : settings.isVisible;
  40264. this.origin = settings.origin || new BABYLON.Vector2(0.5, 0.5);
  40265. // Layout Engine
  40266. if (settings.layoutEngine != null) {
  40267. if (typeof settings.layoutEngine === "string") {
  40268. var name_1 = settings.layoutEngine.toLocaleLowerCase().trim();
  40269. if (name_1 === "canvas" || name_1 === "canvaslayoutengine") {
  40270. this.layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40271. }
  40272. else if (name_1.indexOf("stackpanel") === 0 || name_1.indexOf("horizontalstackpanel") === 0) {
  40273. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Horizontal;
  40274. }
  40275. else if (name_1.indexOf("verticalstackpanel") === 0) {
  40276. this.layoutEngine = BABYLON.StackPanelLayoutEngine.Vertical;
  40277. }
  40278. }
  40279. else if (settings.layoutEngine instanceof BABYLON.LayoutEngineBase) {
  40280. this.layoutEngine = settings.layoutEngine;
  40281. }
  40282. }
  40283. // Set the layout/margin stuffs
  40284. if (settings.marginTop) {
  40285. this.margin.setTop(settings.marginTop);
  40286. }
  40287. if (settings.marginLeft) {
  40288. this.margin.setLeft(settings.marginLeft);
  40289. }
  40290. if (settings.marginRight) {
  40291. this.margin.setRight(settings.marginRight);
  40292. }
  40293. if (settings.marginBottom) {
  40294. this.margin.setBottom(settings.marginBottom);
  40295. }
  40296. if (settings.margin) {
  40297. if (typeof settings.margin === "string") {
  40298. this.margin.fromString(settings.margin);
  40299. }
  40300. else {
  40301. this.margin.fromUniformPixels(settings.margin);
  40302. }
  40303. }
  40304. if (settings.marginHAlignment) {
  40305. this.marginAlignment.horizontal = settings.marginHAlignment;
  40306. }
  40307. if (settings.marginVAlignment) {
  40308. this.marginAlignment.vertical = settings.marginVAlignment;
  40309. }
  40310. if (settings.marginAlignment) {
  40311. this.marginAlignment.fromString(settings.marginAlignment);
  40312. }
  40313. if (settings.paddingTop) {
  40314. this.padding.setTop(settings.paddingTop);
  40315. }
  40316. if (settings.paddingLeft) {
  40317. this.padding.setLeft(settings.paddingLeft);
  40318. }
  40319. if (settings.paddingRight) {
  40320. this.padding.setRight(settings.paddingRight);
  40321. }
  40322. if (settings.paddingBottom) {
  40323. this.padding.setBottom(settings.paddingBottom);
  40324. }
  40325. if (settings.padding) {
  40326. this.padding.fromString(settings.padding);
  40327. }
  40328. // Dirty layout and positioning
  40329. this._parentLayoutDirty();
  40330. this._positioningDirty();
  40331. }
  40332. Object.defineProperty(Prim2DBase.prototype, "actionManager", {
  40333. get: function () {
  40334. if (!this._actionManager) {
  40335. this._actionManager = new BABYLON.ActionManager(this.owner.scene);
  40336. }
  40337. return this._actionManager;
  40338. },
  40339. enumerable: true,
  40340. configurable: true
  40341. });
  40342. /**
  40343. * From 'this' primitive, traverse up (from parent to parent) until the given predicate is true
  40344. * @param predicate the predicate to test on each parent
  40345. * @return the first primitive where the predicate was successful
  40346. */
  40347. Prim2DBase.prototype.traverseUp = function (predicate) {
  40348. var p = this;
  40349. while (p != null) {
  40350. if (predicate(p)) {
  40351. return p;
  40352. }
  40353. p = p._parent;
  40354. }
  40355. return null;
  40356. };
  40357. Object.defineProperty(Prim2DBase.prototype, "owner", {
  40358. /**
  40359. * Retrieve the owner Canvas2D
  40360. */
  40361. get: function () {
  40362. return this._owner;
  40363. },
  40364. enumerable: true,
  40365. configurable: true
  40366. });
  40367. Object.defineProperty(Prim2DBase.prototype, "parent", {
  40368. /**
  40369. * Get the parent primitive (can be the Canvas, only the Canvas has no parent)
  40370. */
  40371. get: function () {
  40372. return this._parent;
  40373. },
  40374. enumerable: true,
  40375. configurable: true
  40376. });
  40377. Object.defineProperty(Prim2DBase.prototype, "children", {
  40378. /**
  40379. * The array of direct children primitives
  40380. */
  40381. get: function () {
  40382. return this._children;
  40383. },
  40384. enumerable: true,
  40385. configurable: true
  40386. });
  40387. Object.defineProperty(Prim2DBase.prototype, "id", {
  40388. /**
  40389. * The identifier of this primitive, may not be unique, it's for information purpose only
  40390. */
  40391. get: function () {
  40392. return this._id;
  40393. },
  40394. enumerable: true,
  40395. configurable: true
  40396. });
  40397. Object.defineProperty(Prim2DBase.prototype, "actualPosition", {
  40398. get: function () {
  40399. if (this._actualPosition != null) {
  40400. return this._actualPosition;
  40401. }
  40402. if (this._position != null) {
  40403. return this._position;
  40404. }
  40405. // At least return 0,0, we can't return null on actualPosition
  40406. return Prim2DBase._nullPosition;
  40407. },
  40408. /**
  40409. * DO NOT INVOKE for internal purpose only
  40410. */
  40411. set: function (val) {
  40412. this._actualPosition = val;
  40413. },
  40414. enumerable: true,
  40415. configurable: true
  40416. });
  40417. Object.defineProperty(Prim2DBase.prototype, "actualX", {
  40418. /**
  40419. * Shortcut to actualPosition.x
  40420. */
  40421. get: function () {
  40422. return this.actualPosition.x;
  40423. },
  40424. enumerable: true,
  40425. configurable: true
  40426. });
  40427. Object.defineProperty(Prim2DBase.prototype, "actualY", {
  40428. /**
  40429. * Shortcut to actualPosition.y
  40430. */
  40431. get: function () {
  40432. return this.actualPosition.y;
  40433. },
  40434. enumerable: true,
  40435. configurable: true
  40436. });
  40437. Object.defineProperty(Prim2DBase.prototype, "position", {
  40438. /**
  40439. * Position of the primitive, relative to its parent.
  40440. * BEWARE: if you change only position.x or y it won't trigger a property change and you won't have the expected behavior.
  40441. * Use this property to set a new Vector2 object, otherwise to change only the x/y use Prim2DBase.x or y properties.
  40442. * Setting this property may have no effect is specific alignment are in effect.
  40443. */
  40444. get: function () {
  40445. return this._position || Prim2DBase._nullPosition;
  40446. },
  40447. set: function (value) {
  40448. if (!this._checkPositionChange()) {
  40449. return;
  40450. }
  40451. this._position = value;
  40452. this.markAsDirty("actualPosition");
  40453. },
  40454. enumerable: true,
  40455. configurable: true
  40456. });
  40457. Object.defineProperty(Prim2DBase.prototype, "x", {
  40458. /**
  40459. * Direct access to the position.x value of the primitive
  40460. * Use this property when you only want to change one component of the position property
  40461. */
  40462. get: function () {
  40463. if (!this._position) {
  40464. return null;
  40465. }
  40466. return this._position.x;
  40467. },
  40468. set: function (value) {
  40469. if (!this._checkPositionChange()) {
  40470. return;
  40471. }
  40472. if (!this._position) {
  40473. this._position = BABYLON.Vector2.Zero();
  40474. }
  40475. if (this._position.x === value) {
  40476. return;
  40477. }
  40478. this._position.x = value;
  40479. this.markAsDirty("position");
  40480. this.markAsDirty("actualPosition");
  40481. },
  40482. enumerable: true,
  40483. configurable: true
  40484. });
  40485. Object.defineProperty(Prim2DBase.prototype, "y", {
  40486. /**
  40487. * Direct access to the position.y value of the primitive
  40488. * Use this property when you only want to change one component of the position property
  40489. */
  40490. get: function () {
  40491. if (!this._position) {
  40492. return null;
  40493. }
  40494. return this._position.y;
  40495. },
  40496. set: function (value) {
  40497. if (!this._checkPositionChange()) {
  40498. return;
  40499. }
  40500. if (!this._position) {
  40501. this._position = BABYLON.Vector2.Zero();
  40502. }
  40503. if (this._position.y === value) {
  40504. return;
  40505. }
  40506. this._position.y = value;
  40507. this.markAsDirty("position");
  40508. this.markAsDirty("actualPosition");
  40509. },
  40510. enumerable: true,
  40511. configurable: true
  40512. });
  40513. Object.defineProperty(Prim2DBase.prototype, "size", {
  40514. /**
  40515. * Size of the primitive or its bounding area
  40516. * BEWARE: if you change only size.width or height it won't trigger a property change and you won't have the expected behavior.
  40517. * Use this property to set a new Size object, otherwise to change only the width/height use Prim2DBase.width or height properties.
  40518. */
  40519. get: function () {
  40520. if (!this._size || this._size.width == null || this._size.height == null) {
  40521. if (Prim2DBase.boundinbBoxReentrency) {
  40522. return Prim2DBase.nullSize;
  40523. }
  40524. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  40525. return this._boundingSize;
  40526. }
  40527. Prim2DBase.boundinbBoxReentrency = true;
  40528. var b = this.boundingInfo;
  40529. Prim2DBase.boundinbBoxReentrency = false;
  40530. return this._boundingSize;
  40531. }
  40532. return this._size;
  40533. },
  40534. set: function (value) {
  40535. this._size = value;
  40536. },
  40537. enumerable: true,
  40538. configurable: true
  40539. });
  40540. Object.defineProperty(Prim2DBase.prototype, "width", {
  40541. /**
  40542. * Direct access to the size.width value of the primitive
  40543. * Use this property when you only want to change one component of the size property
  40544. */
  40545. get: function () {
  40546. if (!this.size) {
  40547. return null;
  40548. }
  40549. return this.size.width;
  40550. },
  40551. set: function (value) {
  40552. if (!this.size) {
  40553. this.size = new BABYLON.Size(value, 0);
  40554. return;
  40555. }
  40556. if (this.size.width === value) {
  40557. return;
  40558. }
  40559. this.size.width = value;
  40560. this.markAsDirty("size");
  40561. this._positioningDirty();
  40562. },
  40563. enumerable: true,
  40564. configurable: true
  40565. });
  40566. Object.defineProperty(Prim2DBase.prototype, "height", {
  40567. /**
  40568. * Direct access to the size.height value of the primitive
  40569. * Use this property when you only want to change one component of the size property
  40570. */
  40571. get: function () {
  40572. if (!this.size) {
  40573. return null;
  40574. }
  40575. return this.size.height;
  40576. },
  40577. set: function (value) {
  40578. if (!this.size) {
  40579. this.size = new BABYLON.Size(0, value);
  40580. return;
  40581. }
  40582. if (this.size.height === value) {
  40583. return;
  40584. }
  40585. this.size.height = value;
  40586. this.markAsDirty("size");
  40587. this._positioningDirty();
  40588. },
  40589. enumerable: true,
  40590. configurable: true
  40591. });
  40592. Object.defineProperty(Prim2DBase.prototype, "rotation", {
  40593. get: function () {
  40594. return this._rotation;
  40595. },
  40596. set: function (value) {
  40597. this._rotation = value;
  40598. },
  40599. enumerable: true,
  40600. configurable: true
  40601. });
  40602. Object.defineProperty(Prim2DBase.prototype, "scale", {
  40603. get: function () {
  40604. return this._scale.x;
  40605. },
  40606. set: function (value) {
  40607. this._scale.x = this._scale.y = value;
  40608. },
  40609. enumerable: true,
  40610. configurable: true
  40611. });
  40612. Object.defineProperty(Prim2DBase.prototype, "actualSize", {
  40613. /**
  40614. * Return the size of the primitive as it's being rendered into the target.
  40615. * This value may be different of the size property when layout/alignment is used or specific primitive types can implement a custom logic through this property.
  40616. * BEWARE: don't use the setter, it's for internal purpose only
  40617. * Note to implementers: you have to override this property and declare if necessary a @xxxxInstanceLevel decorator
  40618. */
  40619. get: function () {
  40620. if (this._actualSize) {
  40621. return this._actualSize;
  40622. }
  40623. return this._size;
  40624. },
  40625. set: function (value) {
  40626. if (this._actualSize.equals(value)) {
  40627. return;
  40628. }
  40629. this._actualSize = value;
  40630. },
  40631. enumerable: true,
  40632. configurable: true
  40633. });
  40634. Object.defineProperty(Prim2DBase.prototype, "actualZOffset", {
  40635. get: function () {
  40636. if (this._manualZOrder != null) {
  40637. return this._manualZOrder;
  40638. }
  40639. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  40640. this._updateZOrder();
  40641. }
  40642. return (1 - this._zOrder);
  40643. },
  40644. enumerable: true,
  40645. configurable: true
  40646. });
  40647. Object.defineProperty(Prim2DBase.prototype, "minSize", {
  40648. /**
  40649. * Get or set the minimal size the Layout Engine should respect when computing the primitive's actualSize.
  40650. * The Primitive's size won't be less than specified.
  40651. * The default value depends of the Primitive type
  40652. */
  40653. get: function () {
  40654. return this._minSize;
  40655. },
  40656. set: function (value) {
  40657. if (this._minSize && value && this._minSize.equals(value)) {
  40658. return;
  40659. }
  40660. this._minSize = value;
  40661. this._parentLayoutDirty();
  40662. },
  40663. enumerable: true,
  40664. configurable: true
  40665. });
  40666. Object.defineProperty(Prim2DBase.prototype, "maxSize", {
  40667. /**
  40668. * Get or set the maximal size the Layout Engine should respect when computing the primitive's actualSize.
  40669. * The Primitive's size won't be more than specified.
  40670. * The default value depends of the Primitive type
  40671. */
  40672. get: function () {
  40673. return this._maxSize;
  40674. },
  40675. set: function (value) {
  40676. if (this._maxSize && value && this._maxSize.equals(value)) {
  40677. return;
  40678. }
  40679. this._maxSize = value;
  40680. this._parentLayoutDirty();
  40681. },
  40682. enumerable: true,
  40683. configurable: true
  40684. });
  40685. Object.defineProperty(Prim2DBase.prototype, "origin", {
  40686. /**
  40687. * The origin defines the normalized coordinate of the center of the primitive, from the bottom/left corner.
  40688. * The origin is used only to compute transformation of the primitive, it has no meaning in the primitive local frame of reference
  40689. * For instance:
  40690. * 0,0 means the center is bottom/left. Which is the default for Canvas2D instances
  40691. * 0.5,0.5 means the center is at the center of the primitive, which is default of all types of Primitives
  40692. * 0,1 means the center is top/left
  40693. * @returns The normalized center.
  40694. */
  40695. get: function () {
  40696. return this._origin;
  40697. },
  40698. set: function (value) {
  40699. this._origin = value;
  40700. },
  40701. enumerable: true,
  40702. configurable: true
  40703. });
  40704. Object.defineProperty(Prim2DBase.prototype, "levelVisible", {
  40705. get: function () {
  40706. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagLevelVisible);
  40707. },
  40708. set: function (value) {
  40709. this._changeFlags(BABYLON.SmartPropertyPrim.flagLevelVisible, value);
  40710. },
  40711. enumerable: true,
  40712. configurable: true
  40713. });
  40714. Object.defineProperty(Prim2DBase.prototype, "isVisible", {
  40715. get: function () {
  40716. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsVisible);
  40717. },
  40718. set: function (value) {
  40719. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsVisible, value);
  40720. },
  40721. enumerable: true,
  40722. configurable: true
  40723. });
  40724. Object.defineProperty(Prim2DBase.prototype, "zOrder", {
  40725. get: function () {
  40726. return this._manualZOrder;
  40727. },
  40728. set: function (value) {
  40729. if (this._manualZOrder === value) {
  40730. return;
  40731. }
  40732. this._manualZOrder = value;
  40733. this.onZOrderChanged();
  40734. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  40735. this._actualZOrderChangedObservable.notifyObservers(value);
  40736. }
  40737. },
  40738. enumerable: true,
  40739. configurable: true
  40740. });
  40741. Object.defineProperty(Prim2DBase.prototype, "isManualZOrder", {
  40742. get: function () {
  40743. return this._manualZOrder != null;
  40744. },
  40745. enumerable: true,
  40746. configurable: true
  40747. });
  40748. Object.defineProperty(Prim2DBase.prototype, "margin", {
  40749. get: function () {
  40750. var _this = this;
  40751. if (!this._margin) {
  40752. this._margin = new PrimitiveThickness(function () {
  40753. if (!_this.parent) {
  40754. return null;
  40755. }
  40756. return _this.parent.margin;
  40757. }, function () { return _this._positioningDirty(); });
  40758. }
  40759. return this._margin;
  40760. },
  40761. enumerable: true,
  40762. configurable: true
  40763. });
  40764. Object.defineProperty(Prim2DBase.prototype, "_hasMargin", {
  40765. get: function () {
  40766. return (this._margin !== null) || (this._marginAlignment !== null);
  40767. },
  40768. enumerable: true,
  40769. configurable: true
  40770. });
  40771. Object.defineProperty(Prim2DBase.prototype, "padding", {
  40772. get: function () {
  40773. var _this = this;
  40774. if (!this._padding) {
  40775. this._padding = new PrimitiveThickness(function () {
  40776. if (!_this.parent) {
  40777. return null;
  40778. }
  40779. return _this.parent.padding;
  40780. }, function () { return _this._positioningDirty(); });
  40781. }
  40782. return this._padding;
  40783. },
  40784. enumerable: true,
  40785. configurable: true
  40786. });
  40787. Object.defineProperty(Prim2DBase.prototype, "_hasPadding", {
  40788. get: function () {
  40789. return this._padding !== null;
  40790. },
  40791. enumerable: true,
  40792. configurable: true
  40793. });
  40794. Object.defineProperty(Prim2DBase.prototype, "marginAlignment", {
  40795. get: function () {
  40796. var _this = this;
  40797. if (!this._marginAlignment) {
  40798. this._marginAlignment = new PrimitiveAlignment(function () { return _this._positioningDirty(); });
  40799. }
  40800. return this._marginAlignment;
  40801. },
  40802. enumerable: true,
  40803. configurable: true
  40804. });
  40805. Object.defineProperty(Prim2DBase.prototype, "opacity", {
  40806. get: function () {
  40807. return this._opacity;
  40808. },
  40809. set: function (value) {
  40810. if (value < 0) {
  40811. value = 0;
  40812. }
  40813. else if (value > 1) {
  40814. value = 1;
  40815. }
  40816. if (this._opacity === value) {
  40817. return;
  40818. }
  40819. this._opacity = value;
  40820. this._updateRenderMode();
  40821. this._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40822. this._spreadActualOpacityChanged();
  40823. },
  40824. enumerable: true,
  40825. configurable: true
  40826. });
  40827. Object.defineProperty(Prim2DBase.prototype, "scaleX", {
  40828. get: function () {
  40829. return this._scale.x;
  40830. },
  40831. set: function (value) {
  40832. this._scale.x = value;
  40833. },
  40834. enumerable: true,
  40835. configurable: true
  40836. });
  40837. Object.defineProperty(Prim2DBase.prototype, "scaleY", {
  40838. get: function () {
  40839. return this._scale.y;
  40840. },
  40841. set: function (value) {
  40842. this._scale.y = value;
  40843. },
  40844. enumerable: true,
  40845. configurable: true
  40846. });
  40847. Object.defineProperty(Prim2DBase.prototype, "actualOpacity", {
  40848. get: function () {
  40849. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagActualOpacityDirty)) {
  40850. var cur = this.parent;
  40851. var op = this.opacity;
  40852. while (cur) {
  40853. op *= cur.opacity;
  40854. cur = cur.parent;
  40855. }
  40856. this._actualOpacity = op;
  40857. this._clearFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  40858. }
  40859. return this._actualOpacity;
  40860. },
  40861. enumerable: true,
  40862. configurable: true
  40863. });
  40864. Object.defineProperty(Prim2DBase.prototype, "layoutEngine", {
  40865. /**
  40866. * Get/set the layout engine to use for this primitive.
  40867. * The default layout engine is the CanvasLayoutEngine.
  40868. */
  40869. get: function () {
  40870. if (!this._layoutEngine) {
  40871. this._layoutEngine = BABYLON.CanvasLayoutEngine.Singleton;
  40872. }
  40873. return this._layoutEngine;
  40874. },
  40875. set: function (value) {
  40876. if (this._layoutEngine === value) {
  40877. return;
  40878. }
  40879. this._changeLayoutEngine(value);
  40880. },
  40881. enumerable: true,
  40882. configurable: true
  40883. });
  40884. Object.defineProperty(Prim2DBase.prototype, "layoutArea", {
  40885. /**
  40886. * Get/set the layout are of this primitive.
  40887. * The Layout area is the zone allocated by the Layout Engine for this particular primitive. Margins/Alignment will be computed based on this area.
  40888. * The setter should only be called by a Layout Engine class.
  40889. */
  40890. get: function () {
  40891. return this._layoutArea;
  40892. },
  40893. set: function (val) {
  40894. if (this._layoutArea.equals(val)) {
  40895. return;
  40896. }
  40897. this._positioningDirty();
  40898. this._layoutArea = val;
  40899. },
  40900. enumerable: true,
  40901. configurable: true
  40902. });
  40903. Object.defineProperty(Prim2DBase.prototype, "layoutAreaPos", {
  40904. /**
  40905. * Get/set the layout area position (relative to the parent primitive).
  40906. * The setter should only be called by a Layout Engine class.
  40907. */
  40908. get: function () {
  40909. return this._layoutAreaPos;
  40910. },
  40911. set: function (val) {
  40912. if (this._layoutAreaPos.equals(val)) {
  40913. return;
  40914. }
  40915. this._positioningDirty();
  40916. this._layoutAreaPos = val;
  40917. },
  40918. enumerable: true,
  40919. configurable: true
  40920. });
  40921. Object.defineProperty(Prim2DBase.prototype, "isPickable", {
  40922. /**
  40923. * Define if the Primitive can be subject to intersection test or not (default is true)
  40924. */
  40925. get: function () {
  40926. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsPickable);
  40927. },
  40928. set: function (value) {
  40929. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsPickable, value);
  40930. },
  40931. enumerable: true,
  40932. configurable: true
  40933. });
  40934. Object.defineProperty(Prim2DBase.prototype, "isContainer", {
  40935. /**
  40936. * Define if the Primitive acts as a container or not
  40937. * A container will encapsulate its children for interaction event.
  40938. * If it's not a container events will be process down to children if the primitive is not pickable.
  40939. * Default value is true
  40940. */
  40941. get: function () {
  40942. return this._isFlagSet(BABYLON.SmartPropertyPrim.flagIsContainer);
  40943. },
  40944. set: function (value) {
  40945. this._changeFlags(BABYLON.SmartPropertyPrim.flagIsContainer, value);
  40946. },
  40947. enumerable: true,
  40948. configurable: true
  40949. });
  40950. Object.defineProperty(Prim2DBase.prototype, "hierarchyDepth", {
  40951. /**
  40952. * Return the depth level of the Primitive into the Canvas' Graph. A Canvas will be 0, its direct children 1, and so on.
  40953. */
  40954. get: function () {
  40955. return this._hierarchyDepth;
  40956. },
  40957. enumerable: true,
  40958. configurable: true
  40959. });
  40960. Object.defineProperty(Prim2DBase.prototype, "renderGroup", {
  40961. /**
  40962. * Retrieve the Group that is responsible to render this primitive
  40963. */
  40964. get: function () {
  40965. return this._renderGroup;
  40966. },
  40967. enumerable: true,
  40968. configurable: true
  40969. });
  40970. Object.defineProperty(Prim2DBase.prototype, "globalTransform", {
  40971. /**
  40972. * Get the global transformation matrix of the primitive
  40973. */
  40974. get: function () {
  40975. this._updateLocalTransform();
  40976. return this._globalTransform;
  40977. },
  40978. enumerable: true,
  40979. configurable: true
  40980. });
  40981. /**
  40982. * return the global position of the primitive, relative to its canvas
  40983. */
  40984. Prim2DBase.prototype.getGlobalPosition = function () {
  40985. var v = new BABYLON.Vector2(0, 0);
  40986. this.getGlobalPositionByRef(v);
  40987. return v;
  40988. };
  40989. /**
  40990. * return the global position of the primitive, relative to its canvas
  40991. * @param v the valid Vector2 object where the global position will be stored
  40992. */
  40993. Prim2DBase.prototype.getGlobalPositionByRef = function (v) {
  40994. v.x = this.globalTransform.m[12];
  40995. v.y = this.globalTransform.m[13];
  40996. };
  40997. Object.defineProperty(Prim2DBase.prototype, "invGlobalTransform", {
  40998. /**
  40999. * Get invert of the global transformation matrix of the primitive
  41000. */
  41001. get: function () {
  41002. this._updateLocalTransform();
  41003. return this._invGlobalTransform;
  41004. },
  41005. enumerable: true,
  41006. configurable: true
  41007. });
  41008. Object.defineProperty(Prim2DBase.prototype, "localTransform", {
  41009. /**
  41010. * Get the local transformation of the primitive
  41011. */
  41012. get: function () {
  41013. this._updateLocalTransform();
  41014. return this._localTransform;
  41015. },
  41016. enumerable: true,
  41017. configurable: true
  41018. });
  41019. Object.defineProperty(Prim2DBase.prototype, "boundingInfo", {
  41020. /**
  41021. * Get the boundingInfo associated to the primitive and its children.
  41022. * The value is supposed to be always up to date
  41023. */
  41024. get: function () {
  41025. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty)) {
  41026. if (this.owner) {
  41027. this.owner.boundingInfoRecomputeCounter.addCount(1, false);
  41028. }
  41029. if (this.isSizedByContent) {
  41030. this._boundingInfo.clear();
  41031. }
  41032. else {
  41033. this._boundingInfo.copyFrom(this.levelBoundingInfo);
  41034. }
  41035. var bi = this._boundingInfo;
  41036. var tps = new BABYLON.BoundingInfo2D();
  41037. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41038. var curChild = _a[_i];
  41039. curChild.boundingInfo.transformToRef(curChild.localTransform, tps);
  41040. bi.unionToRef(tps, bi);
  41041. }
  41042. this._boundingInfo.maxToRef(Prim2DBase._bMax);
  41043. this._boundingSize.copyFromFloats((!this._size || this._size.width == null) ? Math.ceil(Prim2DBase._bMax.x) : this._size.width, (!this._size || this._size.height == null) ? Math.ceil(Prim2DBase._bMax.y) : this._size.height);
  41044. this._clearFlags(BABYLON.SmartPropertyPrim.flagBoundingInfoDirty);
  41045. }
  41046. return this._boundingInfo;
  41047. },
  41048. enumerable: true,
  41049. configurable: true
  41050. });
  41051. Object.defineProperty(Prim2DBase.prototype, "isSizeAuto", {
  41052. /**
  41053. * Determine if the size is automatically computed or fixed because manually specified.
  41054. * Use the actualSize property to get the final/real size of the primitive
  41055. * @returns true if the size is automatically computed, false if it were manually specified.
  41056. */
  41057. get: function () {
  41058. return this._size == null;
  41059. },
  41060. enumerable: true,
  41061. configurable: true
  41062. });
  41063. Object.defineProperty(Prim2DBase.prototype, "isSizedByContent", {
  41064. /**
  41065. * Return true if this prim has an auto size which is set by the children's global bounding box
  41066. */
  41067. get: function () {
  41068. return (this._size == null) && (this._children.length > 0);
  41069. },
  41070. enumerable: true,
  41071. configurable: true
  41072. });
  41073. Object.defineProperty(Prim2DBase.prototype, "isPositionAuto", {
  41074. /**
  41075. * Determine if the position is automatically computed or fixed because manually specified.
  41076. * Use the actualPosition property to get the final/real position of the primitive
  41077. * @returns true if the position is automatically computed, false if it were manually specified.
  41078. */
  41079. get: function () {
  41080. return this._position == null;
  41081. },
  41082. enumerable: true,
  41083. configurable: true
  41084. });
  41085. Object.defineProperty(Prim2DBase.prototype, "pointerEventObservable", {
  41086. /**
  41087. * Interaction with the primitive can be create using this Observable. See the PrimitivePointerInfo class for more information
  41088. */
  41089. get: function () {
  41090. return this._pointerEventObservable;
  41091. },
  41092. enumerable: true,
  41093. configurable: true
  41094. });
  41095. Object.defineProperty(Prim2DBase.prototype, "zActualOrderChangedObservable", {
  41096. get: function () {
  41097. if (!this._actualZOrderChangedObservable) {
  41098. this._actualZOrderChangedObservable = new BABYLON.Observable();
  41099. }
  41100. return this._actualZOrderChangedObservable;
  41101. },
  41102. enumerable: true,
  41103. configurable: true
  41104. });
  41105. Prim2DBase.prototype.findById = function (id) {
  41106. if (this._id === id) {
  41107. return this;
  41108. }
  41109. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41110. var child = _a[_i];
  41111. var r = child.findById(id);
  41112. if (r != null) {
  41113. return r;
  41114. }
  41115. }
  41116. };
  41117. Prim2DBase.prototype.onZOrderChanged = function () {
  41118. };
  41119. Prim2DBase.prototype.levelIntersect = function (intersectInfo) {
  41120. return false;
  41121. };
  41122. /**
  41123. * Capture all the Events of the given PointerId for this primitive.
  41124. * Don't forget to call releasePointerEventsCapture when done.
  41125. * @param pointerId the Id of the pointer to capture the events from.
  41126. */
  41127. Prim2DBase.prototype.setPointerEventCapture = function (pointerId) {
  41128. return this.owner._setPointerCapture(pointerId, this);
  41129. };
  41130. /**
  41131. * Release a captured pointer made with setPointerEventCapture.
  41132. * @param pointerId the Id of the pointer to release the capture from.
  41133. */
  41134. Prim2DBase.prototype.releasePointerEventsCapture = function (pointerId) {
  41135. return this.owner._releasePointerCapture(pointerId, this);
  41136. };
  41137. /**
  41138. * Make an intersection test with the primitive, all inputs/outputs are stored in the IntersectInfo2D class, see its documentation for more information.
  41139. * @param intersectInfo contains the settings of the intersection to perform, to setup before calling this method as well as the result, available after a call to this method.
  41140. */
  41141. Prim2DBase.prototype.intersect = function (intersectInfo) {
  41142. if (!intersectInfo) {
  41143. return false;
  41144. }
  41145. // If this is null it means this method is call for the first level, initialize stuffs
  41146. var firstLevel = !intersectInfo._globalPickPosition;
  41147. if (firstLevel) {
  41148. // Compute the pickPosition in global space and use it to find the local position for each level down, always relative from the world to get the maximum accuracy (and speed). The other way would have been to compute in local every level down relative to its parent's local, which wouldn't be as accurate (even if javascript number is 80bits accurate).
  41149. intersectInfo._globalPickPosition = BABYLON.Vector2.Zero();
  41150. BABYLON.Vector2.TransformToRef(intersectInfo.pickPosition, this.globalTransform, intersectInfo._globalPickPosition);
  41151. intersectInfo._localPickPosition = intersectInfo.pickPosition.clone();
  41152. intersectInfo.intersectedPrimitives = new Array();
  41153. intersectInfo.topMostIntersectedPrimitive = null;
  41154. }
  41155. if (!intersectInfo.intersectHidden && !this.isVisible) {
  41156. return false;
  41157. }
  41158. var id = this.id;
  41159. if (id != null && id.indexOf("__cachedSpriteOfGroup__") === 0) {
  41160. var ownerGroup = this.getExternalData("__cachedGroup__");
  41161. return ownerGroup.intersect(intersectInfo);
  41162. }
  41163. // If we're testing a cachedGroup, we must reject pointer outside its levelBoundingInfo because children primitives could be partially clipped outside so we must not accept them as intersected when it's the case (because they're not visually visible).
  41164. var isIntersectionTest = false;
  41165. if (this instanceof BABYLON.Group2D) {
  41166. var g = this;
  41167. isIntersectionTest = g.isCachedGroup;
  41168. }
  41169. if (isIntersectionTest && !this.levelBoundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41170. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41171. intersectInfo._exit(firstLevel);
  41172. return false;
  41173. }
  41174. // Fast rejection test with boundingInfo
  41175. if (this.isPickable && !this.boundingInfo.doesIntersect(intersectInfo._localPickPosition)) {
  41176. // Important to call this before each return to allow a good recursion next time this intersectInfo is reused
  41177. intersectInfo._exit(firstLevel);
  41178. return false;
  41179. }
  41180. // We hit the boundingInfo that bounds this primitive and its children, now we have to test on the primitive of this level
  41181. var levelIntersectRes = false;
  41182. if (this.isPickable) {
  41183. levelIntersectRes = this.levelIntersect(intersectInfo);
  41184. if (levelIntersectRes) {
  41185. var pii = new PrimitiveIntersectedInfo(this, intersectInfo._localPickPosition.clone());
  41186. intersectInfo.intersectedPrimitives.push(pii);
  41187. if (!intersectInfo.topMostIntersectedPrimitive || (intersectInfo.topMostIntersectedPrimitive.prim.actualZOffset > pii.prim.actualZOffset)) {
  41188. intersectInfo.topMostIntersectedPrimitive = pii;
  41189. }
  41190. // If we must stop at the first intersection, we're done, quit!
  41191. if (intersectInfo.findFirstOnly) {
  41192. intersectInfo._exit(firstLevel);
  41193. return true;
  41194. }
  41195. }
  41196. }
  41197. // Recurse to children if needed
  41198. if (!levelIntersectRes || !intersectInfo.findFirstOnly) {
  41199. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41200. var curChild = _a[_i];
  41201. // Don't test primitive not pick able or if it's hidden and we don't test hidden ones
  41202. if ((!curChild.isPickable && curChild.isContainer) || (!intersectInfo.intersectHidden && !curChild.isVisible)) {
  41203. continue;
  41204. }
  41205. // Must compute the localPickLocation for the children level
  41206. BABYLON.Vector2.TransformToRef(intersectInfo._globalPickPosition, curChild.invGlobalTransform, intersectInfo._localPickPosition);
  41207. // If we got an intersection with the child and we only need to find the first one, quit!
  41208. if (curChild.intersect(intersectInfo) && intersectInfo.findFirstOnly) {
  41209. intersectInfo._exit(firstLevel);
  41210. return true;
  41211. }
  41212. }
  41213. }
  41214. intersectInfo._exit(firstLevel);
  41215. return intersectInfo.isIntersected;
  41216. };
  41217. /**
  41218. * Move a child object into a new position regarding its siblings to change its rendering order.
  41219. * You can also use the shortcut methods to move top/bottom: moveChildToTop, moveChildToBottom, moveToTop, moveToBottom.
  41220. * @param child the object to move
  41221. * @param previous the object which will be before "child", if child has to be the first among sibling, set "previous" to null.
  41222. */
  41223. Prim2DBase.prototype.moveChild = function (child, previous) {
  41224. if (child.parent !== this) {
  41225. return false;
  41226. }
  41227. var childIndex = this._children.indexOf(child);
  41228. var prevIndex = previous ? this._children.indexOf(previous) : -1;
  41229. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41230. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41231. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, prevIndex + 1);
  41232. }
  41233. this._children.splice(prevIndex + 1, 0, this._children.splice(childIndex, 1)[0]);
  41234. return true;
  41235. };
  41236. /**
  41237. * Move the given child so it's displayed on the top of all its siblings
  41238. * @param child the primitive to move to the top
  41239. */
  41240. Prim2DBase.prototype.moveChildToTop = function (child) {
  41241. return this.moveChild(child, this._children[this._children.length - 1]);
  41242. };
  41243. /**
  41244. * Move the given child so it's displayed on the bottom of all its siblings
  41245. * @param child the primitive to move to the top
  41246. */
  41247. Prim2DBase.prototype.moveChildToBottom = function (child) {
  41248. return this.moveChild(child, null);
  41249. };
  41250. /**
  41251. * Move this primitive to be at the top among all its sibling
  41252. */
  41253. Prim2DBase.prototype.moveToTop = function () {
  41254. if (this.parent == null) {
  41255. return false;
  41256. }
  41257. return this.parent.moveChildToTop(this);
  41258. };
  41259. /**
  41260. * Move this primitive to be at the bottom among all its sibling
  41261. */
  41262. Prim2DBase.prototype.moveToBottom = function () {
  41263. if (this.parent == null) {
  41264. return false;
  41265. }
  41266. return this.parent.moveChildToBottom(this);
  41267. };
  41268. Prim2DBase.prototype.addChild = function (child) {
  41269. child._parent = this;
  41270. this._boundingBoxDirty();
  41271. var flat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41272. if (flat) {
  41273. child._setFlags(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41274. child._setZOrder(this._zOrder, true);
  41275. child._zMax = this._zOrder;
  41276. }
  41277. else {
  41278. this._setFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41279. }
  41280. var length = this._children.push(child);
  41281. this._firstZDirtyIndex = Math.min(this._firstZDirtyIndex, length - 1);
  41282. };
  41283. /**
  41284. * Dispose the primitive, remove it from its parent.
  41285. */
  41286. Prim2DBase.prototype.dispose = function () {
  41287. if (!_super.prototype.dispose.call(this)) {
  41288. return false;
  41289. }
  41290. if (this._actionManager) {
  41291. this._actionManager.dispose();
  41292. this._actionManager = null;
  41293. }
  41294. // If there's a parent, remove this object from its parent list
  41295. if (this._parent) {
  41296. var i = this._parent._children.indexOf(this);
  41297. if (i !== undefined) {
  41298. this._parent._children.splice(i, 1);
  41299. }
  41300. this._parent = null;
  41301. }
  41302. // Recurse dispose to children
  41303. if (this._children) {
  41304. while (this._children.length > 0) {
  41305. this._children[this._children.length - 1].dispose();
  41306. }
  41307. }
  41308. return true;
  41309. };
  41310. Prim2DBase.prototype.onPrimBecomesDirty = function () {
  41311. if (this._renderGroup && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPrimInDirtyList)) {
  41312. this._renderGroup._addPrimToDirtyList(this);
  41313. this._setFlags(BABYLON.SmartPropertyPrim.flagPrimInDirtyList);
  41314. }
  41315. };
  41316. Prim2DBase.prototype._needPrepare = function () {
  41317. return this._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged | BABYLON.SmartPropertyPrim.flagModelDirty) || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep);
  41318. };
  41319. Prim2DBase.prototype._prepareRender = function (context) {
  41320. this._prepareRenderPre(context);
  41321. this._prepareRenderPost(context);
  41322. };
  41323. Prim2DBase.prototype._prepareRenderPre = function (context) {
  41324. };
  41325. Prim2DBase.prototype._prepareRenderPost = function (context) {
  41326. // Don't recurse if it's a renderable group, the content will be processed by the group itself
  41327. if (this instanceof BABYLON.Group2D) {
  41328. var self = this;
  41329. if (self.isRenderableGroup) {
  41330. return;
  41331. }
  41332. }
  41333. // Check if we need to recurse the prepare to children primitives
  41334. // - must have children
  41335. // - the global transform of this level have changed, or
  41336. // - the visible state of primitive has changed
  41337. if (this._children.length > 0 && ((this._globalTransformProcessStep !== this._globalTransformStep) ||
  41338. this.checkPropertiesDirty(Prim2DBase.isVisibleProperty.flagId))) {
  41339. this._children.forEach(function (c) {
  41340. // As usual stop the recursion if we meet a renderable group
  41341. if (!(c instanceof BABYLON.Group2D && c.isRenderableGroup)) {
  41342. c._prepareRender(context);
  41343. }
  41344. });
  41345. }
  41346. // Finally reset the dirty flags as we've processed everything
  41347. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  41348. this._instanceDirtyFlags = 0;
  41349. };
  41350. Prim2DBase.prototype._canvasPreInit = function (settings) {
  41351. };
  41352. Prim2DBase.CheckParent = function (parent) {
  41353. //if (!Prim2DBase._isCanvasInit && !parent) {
  41354. // throw new Error("A Primitive needs a valid Parent, it can be any kind of Primitives based types, even the Canvas (with the exception that only Group2D can be direct child of a Canvas if the cache strategy used is TOPLEVELGROUPS)");
  41355. //}
  41356. };
  41357. Prim2DBase.prototype.updateCachedStatesOf = function (list, recurse) {
  41358. for (var _i = 0, list_1 = list; _i < list_1.length; _i++) {
  41359. var cur = list_1[_i];
  41360. cur.updateCachedStates(recurse);
  41361. }
  41362. };
  41363. Prim2DBase.prototype._parentLayoutDirty = function () {
  41364. if (!this._parent || this._parent.isDisposed) {
  41365. return;
  41366. }
  41367. this._parent._setLayoutDirty();
  41368. };
  41369. Prim2DBase.prototype._setLayoutDirty = function () {
  41370. this.onPrimBecomesDirty();
  41371. this._setFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41372. };
  41373. Prim2DBase.prototype._checkPositionChange = function () {
  41374. if (this.parent && this.parent.layoutEngine.isChildPositionAllowed === false) {
  41375. console.log("Can't manually set the position of " + this.id + ", the Layout Engine of its parent doesn't allow it");
  41376. return false;
  41377. }
  41378. return true;
  41379. };
  41380. Prim2DBase.prototype._positioningDirty = function () {
  41381. this.onPrimBecomesDirty();
  41382. this._setFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41383. };
  41384. Prim2DBase.prototype._spreadActualOpacityChanged = function () {
  41385. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41386. var child = _a[_i];
  41387. child._setFlags(BABYLON.SmartPropertyPrim.flagActualOpacityDirty);
  41388. child._spreadActualOpacityChanged();
  41389. }
  41390. };
  41391. Prim2DBase.prototype._changeLayoutEngine = function (engine) {
  41392. this._layoutEngine = engine;
  41393. };
  41394. Prim2DBase.prototype._updateLocalTransform = function () {
  41395. var tflags = Prim2DBase.actualPositionProperty.flagId | Prim2DBase.rotationProperty.flagId | Prim2DBase.scaleProperty.flagId | Prim2DBase.scaleXProperty.flagId | Prim2DBase.scaleYProperty.flagId | Prim2DBase.originProperty.flagId;
  41396. if (this.checkPropertiesDirty(tflags)) {
  41397. if (this.owner) {
  41398. this.owner.addupdateLocalTransformCounter(1);
  41399. }
  41400. var rot = BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), this._rotation);
  41401. var local;
  41402. var pos = this.position;
  41403. if (this._origin.x === 0 && this._origin.y === 0) {
  41404. local = BABYLON.Matrix.Compose(new BABYLON.Vector3(this._scale.x, this._scale.y, 1), rot, new BABYLON.Vector3(pos.x, pos.y, 0));
  41405. this._localTransform = local;
  41406. }
  41407. else {
  41408. // -Origin offset
  41409. var as = this.actualSize;
  41410. BABYLON.Matrix.TranslationToRef((-as.width * this._origin.x), (-as.height * this._origin.y), 0, Prim2DBase._t0);
  41411. // -Origin * rotation
  41412. rot.toRotationMatrix(Prim2DBase._t1);
  41413. Prim2DBase._t0.multiplyToRef(Prim2DBase._t1, Prim2DBase._t2);
  41414. // -Origin * rotation * scale
  41415. BABYLON.Matrix.ScalingToRef(this._scale.x, this._scale.y, 1, Prim2DBase._t0);
  41416. Prim2DBase._t2.multiplyToRef(Prim2DBase._t0, Prim2DBase._t1);
  41417. // -Origin * rotation * scale * (Origin + Position)
  41418. BABYLON.Matrix.TranslationToRef((as.width * this._origin.x) + pos.x, (as.height * this._origin.y) + pos.y, 0, Prim2DBase._t2);
  41419. Prim2DBase._t1.multiplyToRef(Prim2DBase._t2, this._localTransform);
  41420. }
  41421. this.clearPropertiesDirty(tflags);
  41422. return true;
  41423. }
  41424. return false;
  41425. };
  41426. Prim2DBase.prototype.updateCachedStates = function (recurse) {
  41427. if (this.isDisposed) {
  41428. return;
  41429. }
  41430. this.owner.addCachedGroupRenderCounter(1);
  41431. // Check if the parent is synced
  41432. if (this._parent && ((this._parent._globalTransformProcessStep !== this.owner._globalTransformProcessStep) || this._parent._areSomeFlagsSet(BABYLON.SmartPropertyPrim.flagLayoutDirty | BABYLON.SmartPropertyPrim.flagPositioningDirty | BABYLON.SmartPropertyPrim.flagZOrderDirty))) {
  41433. this._parent.updateCachedStates(false);
  41434. }
  41435. // Update Z-Order if needed
  41436. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41437. this._updateZOrder();
  41438. }
  41439. // Update actualSize only if there' not positioning to recompute and the size changed
  41440. // Otherwise positioning will take care of it.
  41441. var sizeDirty = this.checkPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41442. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty) && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) && sizeDirty) {
  41443. var size = this.size;
  41444. if (size) {
  41445. if (this.size.width != null) {
  41446. this.actualSize.width = this.size.width;
  41447. }
  41448. if (this.size.height != null) {
  41449. this.actualSize.height = this.size.height;
  41450. }
  41451. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41452. }
  41453. }
  41454. // Check for layout update
  41455. var positioningDirty = this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41456. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  41457. this.owner.addUpdateLayoutCounter(1);
  41458. this._layoutEngine.updateLayout(this);
  41459. this._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  41460. }
  41461. var positioningComputed = positioningDirty && !this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41462. var autoContentChanged = false;
  41463. if (this.isSizeAuto) {
  41464. if (!this._lastAutoSizeArea) {
  41465. autoContentChanged = this.size !== null;
  41466. }
  41467. else {
  41468. autoContentChanged = (!this._lastAutoSizeArea.equals(this.size));
  41469. }
  41470. }
  41471. // Check for positioning update
  41472. if (!positioningComputed && (autoContentChanged || sizeDirty || this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty) || (this._parent && !this._parent.contentArea.equals(this._parentContentArea)))) {
  41473. this._updatePositioning();
  41474. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41475. if (sizeDirty) {
  41476. this.clearPropertiesDirty(Prim2DBase.sizeProperty.flagId);
  41477. }
  41478. positioningComputed = true;
  41479. }
  41480. if (positioningComputed && this._parent) {
  41481. this._parentContentArea.copyFrom(this._parent.contentArea);
  41482. }
  41483. // Check if we must update this prim
  41484. if (this === this.owner || this._globalTransformProcessStep !== this.owner._globalTransformProcessStep) {
  41485. this.owner.addUpdateGlobalTransformCounter(1);
  41486. var curVisibleState = this.isVisible;
  41487. this.isVisible = (!this._parent || this._parent.isVisible) && this.levelVisible;
  41488. // Detect a change of visibility
  41489. this._changeFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged, curVisibleState !== this.isVisible);
  41490. // Get/compute the localTransform
  41491. var localDirty = this._updateLocalTransform();
  41492. var parentPaddingChanged = false;
  41493. var parentPaddingOffset = Prim2DBase._v0;
  41494. if (this._parent) {
  41495. parentPaddingOffset = this._parent._paddingOffset;
  41496. parentPaddingChanged = !parentPaddingOffset.equals(this._parentPaddingOffset);
  41497. }
  41498. // Check if there are changes in the parent that will force us to update the global matrix
  41499. var parentDirty = (this._parent != null) ? (this._parent._globalTransformStep !== this._parentTransformStep) : false;
  41500. // Check if we have to update the globalTransform
  41501. if (!this._globalTransform || localDirty || parentDirty || parentPaddingChanged) {
  41502. var globalTransform = this._parent ? this._parent._globalTransform : null;
  41503. var localTransform = void 0;
  41504. Prim2DBase._transMtx.copyFrom(this._localTransform);
  41505. Prim2DBase._transMtx.m[12] += this._layoutAreaPos.x + this._marginOffset.x + parentPaddingOffset.x;
  41506. Prim2DBase._transMtx.m[13] += this._layoutAreaPos.y + this._marginOffset.y + parentPaddingOffset.y;
  41507. localTransform = Prim2DBase._transMtx;
  41508. this._globalTransform = this._parent ? localTransform.multiply(globalTransform) : localTransform.clone();
  41509. this._invGlobalTransform = BABYLON.Matrix.Invert(this._globalTransform);
  41510. this._globalTransformStep = this.owner._globalTransformProcessStep + 1;
  41511. this._parentTransformStep = this._parent ? this._parent._globalTransformStep : 0;
  41512. }
  41513. this._globalTransformProcessStep = this.owner._globalTransformProcessStep;
  41514. }
  41515. if (recurse) {
  41516. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41517. var child = _a[_i];
  41518. // Stop the recursion if we meet a renderable group
  41519. child.updateCachedStates(!(child instanceof BABYLON.Group2D && child.isRenderableGroup));
  41520. }
  41521. }
  41522. };
  41523. Prim2DBase.prototype._updatePositioning = function () {
  41524. if (this.owner) {
  41525. this.owner.addUpdatePositioningCounter(1);
  41526. }
  41527. // From this point we assume that the primitive layoutArea is computed and up to date.
  41528. // We know have to :
  41529. // 1. Determine the PaddingArea and the ActualPosition based on the margin/marginAlignment properties, which will also set the size property of the primitive
  41530. // 2. Determine the contentArea based on the padding property.
  41531. // Auto Create PaddingArea if there's no actualSize on width&|height to allocate the whole content available to the paddingArea where the actualSize is null
  41532. if (!this._hasMargin && (this.actualSize.width == null || this.actualSize.height == null)) {
  41533. if (this.actualSize.width == null) {
  41534. this.marginAlignment.horizontal = PrimitiveAlignment.AlignStretch;
  41535. }
  41536. if (this.actualSize.height == null) {
  41537. this.marginAlignment.vertical = PrimitiveAlignment.AlignStretch;
  41538. }
  41539. }
  41540. // Apply margin
  41541. if (this._hasMargin) {
  41542. this.margin.computeWithAlignment(this.layoutArea, this.size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  41543. this.actualSize = Prim2DBase._size.clone();
  41544. }
  41545. var isSizeAuto = this.isSizeAuto;
  41546. if (this._hasPadding) {
  41547. // Two cases from here: the size of the Primitive is Auto, its content can't be shrink, so me resize the primitive itself
  41548. if (isSizeAuto) {
  41549. var content = this.size.clone();
  41550. this._getActualSizeFromContentToRef(content, Prim2DBase._icArea);
  41551. this.padding.enlarge(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  41552. this._contentArea.copyFrom(content);
  41553. this.actualSize = Prim2DBase._size.clone();
  41554. // Changing the padding has resize the prim, which forces us to recompute margin again
  41555. if (this._hasMargin) {
  41556. this.margin.computeWithAlignment(this.layoutArea, Prim2DBase._size, this.marginAlignment, this._marginOffset, Prim2DBase._size);
  41557. }
  41558. }
  41559. else {
  41560. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  41561. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  41562. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  41563. this.padding.compute(Prim2DBase._icArea, this._paddingOffset, Prim2DBase._size);
  41564. this._paddingOffset.x += Prim2DBase._icPos.x;
  41565. this._paddingOffset.y += Prim2DBase._icPos.y;
  41566. this._contentArea.copyFrom(Prim2DBase._size);
  41567. }
  41568. }
  41569. else {
  41570. this._getInitialContentAreaToRef(this.actualSize, Prim2DBase._icPos, Prim2DBase._icArea);
  41571. Prim2DBase._icArea.width = Math.max(0, Prim2DBase._icArea.width);
  41572. Prim2DBase._icArea.height = Math.max(0, Prim2DBase._icArea.height);
  41573. this._paddingOffset.copyFrom(Prim2DBase._icPos);
  41574. this._contentArea.copyFrom(Prim2DBase._icArea);
  41575. }
  41576. if (!this._position) {
  41577. var aPos = new BABYLON.Vector2(this._layoutAreaPos.x + this._marginOffset.x, this._layoutAreaPos.y + this._marginOffset.y);
  41578. this.actualPosition = aPos;
  41579. }
  41580. if (isSizeAuto) {
  41581. this._lastAutoSizeArea = this.size;
  41582. }
  41583. };
  41584. Object.defineProperty(Prim2DBase.prototype, "contentArea", {
  41585. /**
  41586. * Get the content are of this primitive, this area is computed using the padding property and also possibly the primitive type itself.
  41587. * Children of this primitive will be positioned relative to the bottom/left corner of this area.
  41588. */
  41589. get: function () {
  41590. // Check for positioning update
  41591. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagPositioningDirty)) {
  41592. this._updatePositioning();
  41593. this._clearFlags(BABYLON.SmartPropertyPrim.flagPositioningDirty);
  41594. }
  41595. return this._contentArea;
  41596. },
  41597. enumerable: true,
  41598. configurable: true
  41599. });
  41600. Prim2DBase.prototype._patchHierarchy = function (owner) {
  41601. this._owner = owner;
  41602. // The only place we initialize the _renderGroup is this method, if it's set, we already been there, no need to execute more
  41603. if (this._renderGroup != null) {
  41604. return;
  41605. }
  41606. if (this instanceof BABYLON.Group2D) {
  41607. var group = this;
  41608. group.detectGroupStates();
  41609. if (group._trackedNode && !group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  41610. group.owner._registerTrackedNode(this);
  41611. }
  41612. }
  41613. this._renderGroup = this.traverseUp(function (p) { return p instanceof BABYLON.Group2D && p.isRenderableGroup; });
  41614. if (this._parent) {
  41615. this._parentLayoutDirty();
  41616. }
  41617. // Make sure the prim is in the dirtyList if it should be
  41618. if (this._renderGroup && this.isDirty) {
  41619. var list = this._renderGroup._renderableData._primDirtyList;
  41620. var i = list.indexOf(this);
  41621. if (i === -1) {
  41622. list.push(this);
  41623. }
  41624. }
  41625. // Recurse
  41626. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41627. var child = _a[_i];
  41628. child._hierarchyDepth = this._hierarchyDepth + 1;
  41629. child._patchHierarchy(owner);
  41630. }
  41631. };
  41632. Prim2DBase.prototype._updateZOrder = function () {
  41633. var prevLinPos = this._primLinearPosition;
  41634. var startI = 0;
  41635. var startZ = this._zOrder;
  41636. // We must start rebuilding Z-Order from the Prim before the first one that changed, because we know its Z-Order is correct, so are its children, but it's better to recompute everything from this point instead of finding the last valid children
  41637. var childrenCount = this._children.length;
  41638. if (this._firstZDirtyIndex > 0) {
  41639. if ((this._firstZDirtyIndex - 1) < childrenCount) {
  41640. var prevPrim = this._children[this._firstZDirtyIndex - 1];
  41641. prevLinPos = prevPrim._primLinearPosition;
  41642. startI = this._firstZDirtyIndex - 1;
  41643. startZ = prevPrim._zOrder;
  41644. }
  41645. }
  41646. var startPos = prevLinPos;
  41647. // Update the linear position of the primitive from the first one to the last inside this primitive, compute the total number of prim traversed
  41648. Prim2DBase._totalCount = 0;
  41649. for (var i = startI; i < childrenCount; i++) {
  41650. var child = this._children[i];
  41651. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  41652. }
  41653. // Compute the new Z-Order for all the primitives
  41654. // Add 20% to the current total count to reserve space for future insertions, except if we're rebuilding due to a zMinDelta reached
  41655. var zDelta = (this._zMax - startZ) / (Prim2DBase._totalCount * (Prim2DBase._zRebuildReentrency ? 1 : 1.2));
  41656. // If the computed delta is less than the smallest allowed by the depth buffer, we rebuild the Z-Order from the very beginning of the primitive's children (that is, the first) to redistribute uniformly the Z.
  41657. if (zDelta < BABYLON.Canvas2D._zMinDelta) {
  41658. // Check for re-entrance, if the flag is true we already attempted a rebuild but couldn't get a better zDelta, go up in the hierarchy to rebuilt one level up, hoping to get this time a decent delta, otherwise, recurse until we got it or when no parent is reached, which would mean the canvas would have more than 16 millions of primitives...
  41659. if (Prim2DBase._zRebuildReentrency) {
  41660. var p = this._parent;
  41661. if (p == null) {
  41662. // Can't find a good Z delta and we're in the canvas, which mean we're dealing with too many objects (which should never happen, but well...)
  41663. console.log("Can't compute Z-Order for " + this.id + "'s children, zDelta is too small, Z-Order is now in an unstable state");
  41664. Prim2DBase._zRebuildReentrency = false;
  41665. return;
  41666. }
  41667. p._firstZDirtyIndex = 0;
  41668. return p._updateZOrder();
  41669. }
  41670. Prim2DBase._zRebuildReentrency = true;
  41671. this._firstZDirtyIndex = 0;
  41672. this._updateZOrder();
  41673. Prim2DBase._zRebuildReentrency = false;
  41674. }
  41675. for (var i = startI; i < childrenCount; i++) {
  41676. var child = this._children[i];
  41677. child._updatePrimitiveZOrder(startPos, startZ, zDelta);
  41678. }
  41679. // Notify the Observers that we found during the Z change (we do it after to avoid any kind of re-entrance)
  41680. for (var _i = 0, _a = Prim2DBase._zOrderChangedNotifList; _i < _a.length; _i++) {
  41681. var p = _a[_i];
  41682. p._actualZOrderChangedObservable.notifyObservers(p.actualZOffset);
  41683. }
  41684. Prim2DBase._zOrderChangedNotifList.splice(0);
  41685. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41686. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41687. };
  41688. Prim2DBase.prototype._updatePrimitiveLinearPosition = function (prevLinPos) {
  41689. if (this.isManualZOrder) {
  41690. return prevLinPos;
  41691. }
  41692. this._primLinearPosition = ++prevLinPos;
  41693. Prim2DBase._totalCount++;
  41694. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  41695. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder)) {
  41696. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41697. var child = _a[_i];
  41698. prevLinPos = child._updatePrimitiveLinearPosition(prevLinPos);
  41699. }
  41700. }
  41701. return prevLinPos;
  41702. };
  41703. Prim2DBase.prototype._updatePrimitiveZOrder = function (startPos, startZ, deltaZ) {
  41704. if (this.isManualZOrder) {
  41705. return null;
  41706. }
  41707. var newZ = startZ + ((this._primLinearPosition - startPos) * deltaZ);
  41708. var isFlat = this._isFlagSet(BABYLON.SmartPropertyPrim.flagChildrenFlatZOrder);
  41709. this._setZOrder(newZ, false);
  41710. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41711. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41712. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41713. }
  41714. var curZ = newZ;
  41715. // Check for the FlatZOrder, which means the children won't have a dedicated Z-Order but will all share the same (unique) one.
  41716. if (isFlat) {
  41717. if (this._children.length > 0) {
  41718. //let childrenZOrder = startZ + ((this._children[0]._primLinearPosition - startPos) * deltaZ);
  41719. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41720. var child = _a[_i];
  41721. child._updatePrimitiveFlatZOrder(this._zOrder);
  41722. }
  41723. }
  41724. }
  41725. else {
  41726. for (var _b = 0, _c = this._children; _b < _c.length; _b++) {
  41727. var child = _c[_b];
  41728. var r = child._updatePrimitiveZOrder(startPos, startZ, deltaZ);
  41729. if (r != null) {
  41730. curZ = r;
  41731. }
  41732. }
  41733. }
  41734. this._zMax = isFlat ? newZ : (curZ + deltaZ);
  41735. return curZ;
  41736. };
  41737. Prim2DBase.prototype._updatePrimitiveFlatZOrder = function (newZ) {
  41738. if (this.isManualZOrder) {
  41739. return;
  41740. }
  41741. this._setZOrder(newZ, false);
  41742. this._zMax = newZ;
  41743. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagZOrderDirty)) {
  41744. this._firstZDirtyIndex = Prim2DBase._bigInt;
  41745. this._clearFlags(BABYLON.SmartPropertyPrim.flagZOrderDirty);
  41746. }
  41747. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  41748. var child = _a[_i];
  41749. child._updatePrimitiveFlatZOrder(newZ);
  41750. }
  41751. };
  41752. Prim2DBase.prototype._setZOrder = function (newZ, directEmit) {
  41753. if (newZ !== this._zOrder) {
  41754. this._zOrder = newZ;
  41755. this.onPrimBecomesDirty();
  41756. this.onZOrderChanged();
  41757. if (this._actualZOrderChangedObservable && this._actualZOrderChangedObservable.hasObservers()) {
  41758. if (directEmit) {
  41759. this._actualZOrderChangedObservable.notifyObservers(newZ);
  41760. }
  41761. else {
  41762. Prim2DBase._zOrderChangedNotifList.push(this);
  41763. }
  41764. }
  41765. }
  41766. };
  41767. Prim2DBase.prototype._updateRenderMode = function () {
  41768. };
  41769. /**
  41770. * This method is used to alter the contentArea of the Primitive before margin is applied.
  41771. * In most of the case you won't need to override this method, but it can prove some usefulness, check the Rectangle2D class for a concrete application.
  41772. * @param primSize the current size of the primitive
  41773. * @param initialContentPosition the position of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing!
  41774. * @param initialContentArea the size of the initial content area to compute, a valid object is passed, you have to set its properties. PLEASE ROUND the values, we're talking about pixels and fraction of them is not a good thing!
  41775. */
  41776. Prim2DBase.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  41777. initialContentArea.copyFrom(primSize);
  41778. initialContentPosition.x = initialContentPosition.y = 0;
  41779. };
  41780. /**
  41781. * This method is used to calculate the new size of the primitive based on the content which must stay the same
  41782. * Check the Rectangle2D implementation for a concrete application.
  41783. * @param primSize the current size of the primitive
  41784. * @param newPrimSize the new size of the primitive. PLEASE ROUND THE values, we're talking about pixels and fraction of them are not our friends!
  41785. */
  41786. Prim2DBase.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  41787. newPrimSize.copyFrom(primSize);
  41788. };
  41789. Prim2DBase.PRIM2DBASE_PROPCOUNT = 16;
  41790. Prim2DBase._bigInt = Math.pow(2, 30);
  41791. Prim2DBase._nullPosition = BABYLON.Vector2.Zero();
  41792. Prim2DBase.boundinbBoxReentrency = false;
  41793. Prim2DBase.nullSize = BABYLON.Size.Zero();
  41794. Prim2DBase._bMax = BABYLON.Vector2.Zero();
  41795. Prim2DBase._isCanvasInit = false;
  41796. Prim2DBase._t0 = new BABYLON.Matrix();
  41797. Prim2DBase._t1 = new BABYLON.Matrix();
  41798. Prim2DBase._t2 = new BABYLON.Matrix();
  41799. Prim2DBase._v0 = BABYLON.Vector2.Zero(); // Must stay with the value 0,0
  41800. Prim2DBase._transMtx = BABYLON.Matrix.Zero();
  41801. Prim2DBase._icPos = BABYLON.Vector2.Zero();
  41802. Prim2DBase._icArea = BABYLON.Size.Zero();
  41803. Prim2DBase._size = BABYLON.Size.Zero();
  41804. Prim2DBase._zOrderChangedNotifList = new Array();
  41805. Prim2DBase._zRebuildReentrency = false;
  41806. Prim2DBase._totalCount = 0;
  41807. __decorate([
  41808. BABYLON.instanceLevelProperty(1, function (pi) { return Prim2DBase.actualPositionProperty = pi; }, false, false, true)
  41809. ], Prim2DBase.prototype, "actualPosition", null);
  41810. __decorate([
  41811. BABYLON.dynamicLevelProperty(2, function (pi) { return Prim2DBase.positionProperty = pi; }, false, false, true)
  41812. ], Prim2DBase.prototype, "position", null);
  41813. __decorate([
  41814. BABYLON.dynamicLevelProperty(3, function (pi) { return Prim2DBase.sizeProperty = pi; }, false, true)
  41815. ], Prim2DBase.prototype, "size", null);
  41816. __decorate([
  41817. BABYLON.instanceLevelProperty(4, function (pi) { return Prim2DBase.rotationProperty = pi; }, false, true)
  41818. ], Prim2DBase.prototype, "rotation", null);
  41819. __decorate([
  41820. BABYLON.instanceLevelProperty(5, function (pi) { return Prim2DBase.scaleProperty = pi; }, false, true)
  41821. ], Prim2DBase.prototype, "scale", null);
  41822. __decorate([
  41823. BABYLON.dynamicLevelProperty(6, function (pi) { return Prim2DBase.originProperty = pi; }, false, true)
  41824. ], Prim2DBase.prototype, "origin", null);
  41825. __decorate([
  41826. BABYLON.dynamicLevelProperty(7, function (pi) { return Prim2DBase.levelVisibleProperty = pi; })
  41827. ], Prim2DBase.prototype, "levelVisible", null);
  41828. __decorate([
  41829. BABYLON.instanceLevelProperty(8, function (pi) { return Prim2DBase.isVisibleProperty = pi; })
  41830. ], Prim2DBase.prototype, "isVisible", null);
  41831. __decorate([
  41832. BABYLON.instanceLevelProperty(9, function (pi) { return Prim2DBase.zOrderProperty = pi; })
  41833. ], Prim2DBase.prototype, "zOrder", null);
  41834. __decorate([
  41835. BABYLON.dynamicLevelProperty(10, function (pi) { return Prim2DBase.marginProperty = pi; })
  41836. ], Prim2DBase.prototype, "margin", null);
  41837. __decorate([
  41838. BABYLON.dynamicLevelProperty(11, function (pi) { return Prim2DBase.paddingProperty = pi; })
  41839. ], Prim2DBase.prototype, "padding", null);
  41840. __decorate([
  41841. BABYLON.dynamicLevelProperty(12, function (pi) { return Prim2DBase.marginAlignmentProperty = pi; })
  41842. ], Prim2DBase.prototype, "marginAlignment", null);
  41843. __decorate([
  41844. BABYLON.instanceLevelProperty(13, function (pi) { return Prim2DBase.opacityProperty = pi; })
  41845. ], Prim2DBase.prototype, "opacity", null);
  41846. __decorate([
  41847. BABYLON.instanceLevelProperty(14, function (pi) { return Prim2DBase.scaleXProperty = pi; }, false, true)
  41848. ], Prim2DBase.prototype, "scaleX", null);
  41849. __decorate([
  41850. BABYLON.instanceLevelProperty(15, function (pi) { return Prim2DBase.scaleYProperty = pi; }, false, true)
  41851. ], Prim2DBase.prototype, "scaleY", null);
  41852. Prim2DBase = __decorate([
  41853. BABYLON.className("Prim2DBase")
  41854. ], Prim2DBase);
  41855. return Prim2DBase;
  41856. }(BABYLON.SmartPropertyPrim));
  41857. BABYLON.Prim2DBase = Prim2DBase;
  41858. })(BABYLON || (BABYLON = {}));
  41859. var BABYLON;
  41860. (function (BABYLON) {
  41861. var GroupInstanceInfo = (function () {
  41862. function GroupInstanceInfo(owner, mrc, partCount) {
  41863. this._partCount = partCount;
  41864. this.owner = owner;
  41865. this.modelRenderCache = mrc;
  41866. this.modelRenderCache.addRef();
  41867. this.partIndexFromId = new BABYLON.StringDictionary();
  41868. this._usedShaderCategories = new Array(partCount);
  41869. this._strides = new Array(partCount);
  41870. this._opaqueData = null;
  41871. this._alphaTestData = null;
  41872. this._transparentData = null;
  41873. this.opaqueDirty = this.alphaTestDirty = this.transparentDirty = this.transparentOrderDirty = false;
  41874. }
  41875. GroupInstanceInfo.prototype.dispose = function () {
  41876. if (this._isDisposed) {
  41877. return false;
  41878. }
  41879. if (this.modelRenderCache) {
  41880. this.modelRenderCache.dispose();
  41881. this.modelRenderCache = null;
  41882. }
  41883. var engine = this.owner.owner.engine;
  41884. if (this._opaqueData) {
  41885. this._opaqueData.forEach(function (d) { return d.dispose(engine); });
  41886. this._opaqueData = null;
  41887. }
  41888. if (this._alphaTestData) {
  41889. this._alphaTestData.forEach(function (d) { return d.dispose(engine); });
  41890. this._alphaTestData = null;
  41891. }
  41892. if (this._transparentData) {
  41893. this._transparentData.forEach(function (d) { return d.dispose(engine); });
  41894. this._transparentData = null;
  41895. }
  41896. this.partIndexFromId = null;
  41897. this._isDisposed = true;
  41898. return true;
  41899. };
  41900. Object.defineProperty(GroupInstanceInfo.prototype, "hasOpaqueData", {
  41901. get: function () {
  41902. return this._opaqueData != null;
  41903. },
  41904. enumerable: true,
  41905. configurable: true
  41906. });
  41907. Object.defineProperty(GroupInstanceInfo.prototype, "hasAlphaTestData", {
  41908. get: function () {
  41909. return this._alphaTestData != null;
  41910. },
  41911. enumerable: true,
  41912. configurable: true
  41913. });
  41914. Object.defineProperty(GroupInstanceInfo.prototype, "hasTransparentData", {
  41915. get: function () {
  41916. return this._transparentData != null;
  41917. },
  41918. enumerable: true,
  41919. configurable: true
  41920. });
  41921. Object.defineProperty(GroupInstanceInfo.prototype, "opaqueData", {
  41922. get: function () {
  41923. if (!this._opaqueData) {
  41924. this._opaqueData = new Array(this._partCount);
  41925. for (var i = 0; i < this._partCount; i++) {
  41926. this._opaqueData[i] = new GroupInfoPartData(this._strides[i]);
  41927. }
  41928. }
  41929. return this._opaqueData;
  41930. },
  41931. enumerable: true,
  41932. configurable: true
  41933. });
  41934. Object.defineProperty(GroupInstanceInfo.prototype, "alphaTestData", {
  41935. get: function () {
  41936. if (!this._alphaTestData) {
  41937. this._alphaTestData = new Array(this._partCount);
  41938. for (var i = 0; i < this._partCount; i++) {
  41939. this._alphaTestData[i] = new GroupInfoPartData(this._strides[i]);
  41940. }
  41941. }
  41942. return this._alphaTestData;
  41943. },
  41944. enumerable: true,
  41945. configurable: true
  41946. });
  41947. Object.defineProperty(GroupInstanceInfo.prototype, "transparentData", {
  41948. get: function () {
  41949. if (!this._transparentData) {
  41950. this._transparentData = new Array(this._partCount);
  41951. for (var i = 0; i < this._partCount; i++) {
  41952. var zoff = this.modelRenderCache._partData[i]._zBiasOffset;
  41953. this._transparentData[i] = new TransparentGroupInfoPartData(this._strides[i], zoff);
  41954. }
  41955. }
  41956. return this._transparentData;
  41957. },
  41958. enumerable: true,
  41959. configurable: true
  41960. });
  41961. GroupInstanceInfo.prototype.sortTransparentData = function () {
  41962. if (!this.transparentOrderDirty) {
  41963. return;
  41964. }
  41965. for (var i = 0; i < this._transparentData.length; i++) {
  41966. var td = this._transparentData[i];
  41967. td._partData.sort();
  41968. }
  41969. this.transparentOrderDirty = false;
  41970. };
  41971. Object.defineProperty(GroupInstanceInfo.prototype, "usedShaderCategories", {
  41972. get: function () {
  41973. return this._usedShaderCategories;
  41974. },
  41975. enumerable: true,
  41976. configurable: true
  41977. });
  41978. Object.defineProperty(GroupInstanceInfo.prototype, "strides", {
  41979. get: function () {
  41980. return this._strides;
  41981. },
  41982. enumerable: true,
  41983. configurable: true
  41984. });
  41985. return GroupInstanceInfo;
  41986. }());
  41987. BABYLON.GroupInstanceInfo = GroupInstanceInfo;
  41988. var TransparentSegment = (function () {
  41989. function TransparentSegment() {
  41990. this.groupInsanceInfo = null;
  41991. this.startZ = 0;
  41992. this.endZ = 0;
  41993. this.startDataIndex = BABYLON.Prim2DBase._bigInt;
  41994. this.endDataIndex = 0;
  41995. this.partBuffers = null;
  41996. }
  41997. TransparentSegment.prototype.dispose = function (engine) {
  41998. if (this.partBuffers) {
  41999. this.partBuffers.forEach(function (b) { return engine._releaseBuffer(b); });
  42000. this.partBuffers.splice(0);
  42001. this.partBuffers = null;
  42002. }
  42003. };
  42004. return TransparentSegment;
  42005. }());
  42006. BABYLON.TransparentSegment = TransparentSegment;
  42007. var GroupInfoPartData = (function () {
  42008. function GroupInfoPartData(stride) {
  42009. this._partData = null;
  42010. this._partBuffer = null;
  42011. this._partBufferSize = 0;
  42012. this._partData = new BABYLON.DynamicFloatArray(stride / 4, 50);
  42013. this._isDisposed = false;
  42014. }
  42015. GroupInfoPartData.prototype.dispose = function (engine) {
  42016. if (this._isDisposed) {
  42017. return false;
  42018. }
  42019. if (this._partBuffer) {
  42020. engine._releaseBuffer(this._partBuffer);
  42021. this._partBuffer = null;
  42022. }
  42023. this._partData = null;
  42024. this._isDisposed = true;
  42025. };
  42026. return GroupInfoPartData;
  42027. }());
  42028. BABYLON.GroupInfoPartData = GroupInfoPartData;
  42029. var TransparentGroupInfoPartData = (function (_super) {
  42030. __extends(TransparentGroupInfoPartData, _super);
  42031. function TransparentGroupInfoPartData(stride, zoff) {
  42032. _super.call(this, stride);
  42033. this._partData.compareValueOffset = zoff;
  42034. this._partData.sortingAscending = false;
  42035. }
  42036. return TransparentGroupInfoPartData;
  42037. }(GroupInfoPartData));
  42038. BABYLON.TransparentGroupInfoPartData = TransparentGroupInfoPartData;
  42039. var ModelRenderCache = (function () {
  42040. function ModelRenderCache(engine, modelKey) {
  42041. this._engine = engine;
  42042. this._modelKey = modelKey;
  42043. this._nextKey = 1;
  42044. this._refCounter = 1;
  42045. this._partData = null;
  42046. }
  42047. ModelRenderCache.prototype.dispose = function () {
  42048. if (--this._refCounter !== 0) {
  42049. return false;
  42050. }
  42051. // Remove the Model Render Cache from the global dictionary
  42052. var edata = this._engine.getExternalData("__BJSCANVAS2D__");
  42053. if (edata) {
  42054. edata.DisposeModelRenderCache(this);
  42055. }
  42056. return true;
  42057. };
  42058. Object.defineProperty(ModelRenderCache.prototype, "isDisposed", {
  42059. get: function () {
  42060. return this._refCounter <= 0;
  42061. },
  42062. enumerable: true,
  42063. configurable: true
  42064. });
  42065. ModelRenderCache.prototype.addRef = function () {
  42066. return ++this._refCounter;
  42067. };
  42068. Object.defineProperty(ModelRenderCache.prototype, "modelKey", {
  42069. get: function () {
  42070. return this._modelKey;
  42071. },
  42072. enumerable: true,
  42073. configurable: true
  42074. });
  42075. /**
  42076. * Render the model instances
  42077. * @param instanceInfo
  42078. * @param context
  42079. * @return must return true is the rendering succeed, false if the rendering couldn't be done (asset's not yet ready, like Effect)
  42080. */
  42081. ModelRenderCache.prototype.render = function (instanceInfo, context) {
  42082. return true;
  42083. };
  42084. ModelRenderCache.prototype.getPartIndexFromId = function (partId) {
  42085. for (var i = 0; i < this._partData.length; i++) {
  42086. if (this._partData[i]._partId === partId) {
  42087. return i;
  42088. }
  42089. }
  42090. return null;
  42091. };
  42092. ModelRenderCache.prototype.loadInstancingAttributes = function (partId, effect) {
  42093. var i = this.getPartIndexFromId(partId);
  42094. if (i === null) {
  42095. return null;
  42096. }
  42097. var ci = this._partsClassInfo[i];
  42098. var categories = this._partData[i]._partUsedCategories;
  42099. var res = ci.classContent.getInstancingAttributeInfos(effect, categories);
  42100. return res;
  42101. };
  42102. ModelRenderCache.prototype.setupUniforms = function (effect, partIndex, data, elementCount) {
  42103. var pd = this._partData[partIndex];
  42104. var offset = (pd._partDataStride / 4) * elementCount;
  42105. var pci = this._partsClassInfo[partIndex];
  42106. var self = this;
  42107. pci.fullContent.forEach(function (k, v) {
  42108. if (!v.category || pd._partUsedCategories.indexOf(v.category) !== -1) {
  42109. switch (v.dataType) {
  42110. case 4 /* float */:
  42111. {
  42112. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42113. effect.setFloat(v.attributeName, data.buffer[offset + attribOffset]);
  42114. break;
  42115. }
  42116. case 0 /* Vector2 */:
  42117. {
  42118. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42119. ModelRenderCache.v2.x = data.buffer[offset + attribOffset + 0];
  42120. ModelRenderCache.v2.y = data.buffer[offset + attribOffset + 1];
  42121. effect.setVector2(v.attributeName, ModelRenderCache.v2);
  42122. break;
  42123. }
  42124. case 5 /* Color3 */:
  42125. case 1 /* Vector3 */:
  42126. {
  42127. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42128. ModelRenderCache.v3.x = data.buffer[offset + attribOffset + 0];
  42129. ModelRenderCache.v3.y = data.buffer[offset + attribOffset + 1];
  42130. ModelRenderCache.v3.z = data.buffer[offset + attribOffset + 2];
  42131. effect.setVector3(v.attributeName, ModelRenderCache.v3);
  42132. break;
  42133. }
  42134. case 6 /* Color4 */:
  42135. case 2 /* Vector4 */:
  42136. {
  42137. var attribOffset = v.instanceOffset.get(pd._partJoinedUsedCategories);
  42138. ModelRenderCache.v4.x = data.buffer[offset + attribOffset + 0];
  42139. ModelRenderCache.v4.y = data.buffer[offset + attribOffset + 1];
  42140. ModelRenderCache.v4.z = data.buffer[offset + attribOffset + 2];
  42141. ModelRenderCache.v4.w = data.buffer[offset + attribOffset + 3];
  42142. effect.setVector4(v.attributeName, ModelRenderCache.v4);
  42143. break;
  42144. }
  42145. default:
  42146. }
  42147. }
  42148. });
  42149. };
  42150. //setupUniformsLocation(effect: Effect, uniforms: string[], partId: number) {
  42151. // let i = this.getPartIndexFromId(partId);
  42152. // if (i === null) {
  42153. // return null;
  42154. // }
  42155. // let pci = this._partsClassInfo[i];
  42156. // pci.fullContent.forEach((k, v) => {
  42157. // if (uniforms.indexOf(v.attributeName) !== -1) {
  42158. // v.uniformLocation = effect.getUniform(v.attributeName);
  42159. // }
  42160. // });
  42161. //}
  42162. ModelRenderCache.v2 = BABYLON.Vector2.Zero();
  42163. ModelRenderCache.v3 = BABYLON.Vector3.Zero();
  42164. ModelRenderCache.v4 = BABYLON.Vector4.Zero();
  42165. return ModelRenderCache;
  42166. }());
  42167. BABYLON.ModelRenderCache = ModelRenderCache;
  42168. var ModelRenderCachePartData = (function () {
  42169. function ModelRenderCachePartData() {
  42170. }
  42171. return ModelRenderCachePartData;
  42172. }());
  42173. BABYLON.ModelRenderCachePartData = ModelRenderCachePartData;
  42174. })(BABYLON || (BABYLON = {}));
  42175. var BABYLON;
  42176. (function (BABYLON) {
  42177. var InstanceClassInfo = (function () {
  42178. function InstanceClassInfo(base) {
  42179. this._baseInfo = base;
  42180. this._nextOffset = new BABYLON.StringDictionary();
  42181. this._attributes = new Array();
  42182. }
  42183. InstanceClassInfo.prototype.mapProperty = function (propInfo, push) {
  42184. var curOff = this._nextOffset.getOrAdd(InstanceClassInfo._CurCategories, 0);
  42185. propInfo.instanceOffset.add(InstanceClassInfo._CurCategories, this._getBaseOffset(InstanceClassInfo._CurCategories) + curOff);
  42186. //console.log(`[${InstanceClassInfo._CurCategories}] New PropInfo. Category: ${propInfo.category}, Name: ${propInfo.attributeName}, Offset: ${propInfo.instanceOffset.get(InstanceClassInfo._CurCategories)}, Size: ${propInfo.size / 4}`);
  42187. this._nextOffset.set(InstanceClassInfo._CurCategories, curOff + (propInfo.size / 4));
  42188. if (push) {
  42189. this._attributes.push(propInfo);
  42190. }
  42191. };
  42192. InstanceClassInfo.prototype.getInstancingAttributeInfos = function (effect, categories) {
  42193. var catInline = ";" + categories.join(";") + ";";
  42194. var res = new Array();
  42195. var curInfo = this;
  42196. while (curInfo) {
  42197. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42198. var attrib = _a[_i];
  42199. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  42200. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42201. var index = effect.getAttributeLocationByName(attrib.attributeName);
  42202. var iai = new BABYLON.InstancingAttributeInfo();
  42203. iai.index = index;
  42204. iai.attributeSize = attrib.size / 4; // attrib.size is in byte and we need to store in "component" (i.e float is 1, vec3 is 3)
  42205. iai.offset = attrib.instanceOffset.get(catInline) * 4; // attrib.instanceOffset is in float, iai.offset must be in bytes
  42206. iai.attributeName = attrib.attributeName;
  42207. res.push(iai);
  42208. }
  42209. }
  42210. curInfo = curInfo._baseInfo;
  42211. }
  42212. return res;
  42213. };
  42214. InstanceClassInfo.prototype.getShaderAttributes = function (categories) {
  42215. var res = new Array();
  42216. var curInfo = this;
  42217. while (curInfo) {
  42218. for (var _i = 0, _a = curInfo._attributes; _i < _a.length; _i++) {
  42219. var attrib = _a[_i];
  42220. // Only map if there's no category assigned to the instance data or if there's a category and it's in the given list
  42221. if (!attrib.category || categories.indexOf(attrib.category) !== -1) {
  42222. res.push(attrib.attributeName);
  42223. }
  42224. }
  42225. curInfo = curInfo._baseInfo;
  42226. }
  42227. return res;
  42228. };
  42229. InstanceClassInfo.prototype._getBaseOffset = function (categories) {
  42230. var curOffset = 0;
  42231. var curBase = this._baseInfo;
  42232. while (curBase) {
  42233. curOffset += curBase._nextOffset.getOrAdd(categories, 0);
  42234. curBase = curBase._baseInfo;
  42235. }
  42236. return curOffset;
  42237. };
  42238. return InstanceClassInfo;
  42239. }());
  42240. BABYLON.InstanceClassInfo = InstanceClassInfo;
  42241. var InstancePropInfo = (function () {
  42242. function InstancePropInfo() {
  42243. this.instanceOffset = new BABYLON.StringDictionary();
  42244. }
  42245. InstancePropInfo.prototype.setSize = function (val) {
  42246. if (val instanceof BABYLON.Vector2) {
  42247. this.size = 8;
  42248. this.dataType = 0 /* Vector2 */;
  42249. return;
  42250. }
  42251. if (val instanceof BABYLON.Vector3) {
  42252. this.size = 12;
  42253. this.dataType = 1 /* Vector3 */;
  42254. return;
  42255. }
  42256. if (val instanceof BABYLON.Vector4) {
  42257. this.size = 16;
  42258. this.dataType = 2 /* Vector4 */;
  42259. return;
  42260. }
  42261. if (val instanceof BABYLON.Matrix) {
  42262. throw new Error("Matrix type is not supported by WebGL Instance Buffer, you have to use four Vector4 properties instead");
  42263. }
  42264. if (typeof (val) === "number") {
  42265. this.size = 4;
  42266. this.dataType = 4 /* float */;
  42267. return;
  42268. }
  42269. if (val instanceof BABYLON.Color3) {
  42270. this.size = 12;
  42271. this.dataType = 5 /* Color3 */;
  42272. return;
  42273. }
  42274. if (val instanceof BABYLON.Color4) {
  42275. this.size = 16;
  42276. this.dataType = 6 /* Color4 */;
  42277. return;
  42278. }
  42279. if (val instanceof BABYLON.Size) {
  42280. this.size = 8;
  42281. this.dataType = 7 /* Size */;
  42282. return;
  42283. }
  42284. return;
  42285. };
  42286. InstancePropInfo.prototype.writeData = function (array, offset, val) {
  42287. switch (this.dataType) {
  42288. case 0 /* Vector2 */:
  42289. {
  42290. var v = val;
  42291. array[offset + 0] = v.x;
  42292. array[offset + 1] = v.y;
  42293. break;
  42294. }
  42295. case 1 /* Vector3 */:
  42296. {
  42297. var v = val;
  42298. array[offset + 0] = v.x;
  42299. array[offset + 1] = v.y;
  42300. array[offset + 2] = v.z;
  42301. break;
  42302. }
  42303. case 2 /* Vector4 */:
  42304. {
  42305. var v = val;
  42306. array[offset + 0] = v.x;
  42307. array[offset + 1] = v.y;
  42308. array[offset + 2] = v.z;
  42309. array[offset + 3] = v.w;
  42310. break;
  42311. }
  42312. case 5 /* Color3 */:
  42313. {
  42314. var v = val;
  42315. array[offset + 0] = v.r;
  42316. array[offset + 1] = v.g;
  42317. array[offset + 2] = v.b;
  42318. break;
  42319. }
  42320. case 6 /* Color4 */:
  42321. {
  42322. var v = val;
  42323. array[offset + 0] = v.r;
  42324. array[offset + 1] = v.g;
  42325. array[offset + 2] = v.b;
  42326. array[offset + 3] = v.a;
  42327. break;
  42328. }
  42329. case 4 /* float */:
  42330. {
  42331. var v = val;
  42332. array[offset] = v;
  42333. break;
  42334. }
  42335. case 3 /* Matrix */:
  42336. {
  42337. var v = val;
  42338. for (var i = 0; i < 16; i++) {
  42339. array[offset + i] = v.m[i];
  42340. }
  42341. break;
  42342. }
  42343. case 7 /* Size */:
  42344. {
  42345. var s = val;
  42346. array[offset + 0] = s.width;
  42347. array[offset + 1] = s.height;
  42348. break;
  42349. }
  42350. }
  42351. };
  42352. return InstancePropInfo;
  42353. }());
  42354. BABYLON.InstancePropInfo = InstancePropInfo;
  42355. function instanceData(category, shaderAttributeName) {
  42356. return function (target, propName, descriptor) {
  42357. var dic = BABYLON.ClassTreeInfo.getOrRegister(target, function (base) { return new InstanceClassInfo(base); });
  42358. var node = dic.getLevelOf(target);
  42359. var instanceDataName = propName;
  42360. shaderAttributeName = shaderAttributeName || instanceDataName;
  42361. var info = node.levelContent.get(instanceDataName);
  42362. if (info) {
  42363. throw new Error("The ID " + instanceDataName + " is already taken by another instance data");
  42364. }
  42365. info = new InstancePropInfo();
  42366. info.attributeName = shaderAttributeName;
  42367. info.category = category || null;
  42368. if (info.category) {
  42369. info.delimitedCategory = ";" + info.category + ";";
  42370. }
  42371. node.levelContent.add(instanceDataName, info);
  42372. descriptor.get = function () {
  42373. return null;
  42374. };
  42375. descriptor.set = function (val) {
  42376. // Check that we're not trying to set a property that belongs to a category that is not allowed (current)
  42377. // Quit if it's the case, otherwise we could overwrite data somewhere...
  42378. if (info.category && InstanceClassInfo._CurCategories.indexOf(info.delimitedCategory) === -1) {
  42379. return;
  42380. }
  42381. if (!info.size) {
  42382. info.setSize(val);
  42383. node.classContent.mapProperty(info, true);
  42384. }
  42385. else if (!info.instanceOffset.contains(InstanceClassInfo._CurCategories)) {
  42386. node.classContent.mapProperty(info, false);
  42387. }
  42388. var obj = this;
  42389. if (obj.dataBuffer && obj.dataElements) {
  42390. var offset = obj.dataElements[obj.curElement].offset + info.instanceOffset.get(InstanceClassInfo._CurCategories);
  42391. info.writeData(obj.dataBuffer.buffer, offset, val);
  42392. }
  42393. };
  42394. };
  42395. }
  42396. BABYLON.instanceData = instanceData;
  42397. var InstanceDataBase = (function () {
  42398. function InstanceDataBase(partId, dataElementCount) {
  42399. this.id = partId;
  42400. this.curElement = 0;
  42401. this._dataElementCount = dataElementCount;
  42402. this.renderMode = 0;
  42403. this.arrayLengthChanged = false;
  42404. }
  42405. Object.defineProperty(InstanceDataBase.prototype, "zBias", {
  42406. get: function () {
  42407. return null;
  42408. },
  42409. enumerable: true,
  42410. configurable: true
  42411. });
  42412. Object.defineProperty(InstanceDataBase.prototype, "transformX", {
  42413. get: function () {
  42414. return null;
  42415. },
  42416. enumerable: true,
  42417. configurable: true
  42418. });
  42419. Object.defineProperty(InstanceDataBase.prototype, "transformY", {
  42420. get: function () {
  42421. return null;
  42422. },
  42423. enumerable: true,
  42424. configurable: true
  42425. });
  42426. Object.defineProperty(InstanceDataBase.prototype, "opacity", {
  42427. get: function () {
  42428. return null;
  42429. },
  42430. enumerable: true,
  42431. configurable: true
  42432. });
  42433. InstanceDataBase.prototype.getClassTreeInfo = function () {
  42434. if (!this.typeInfo) {
  42435. this.typeInfo = BABYLON.ClassTreeInfo.get(Object.getPrototypeOf(this));
  42436. }
  42437. return this.typeInfo;
  42438. };
  42439. InstanceDataBase.prototype.allocElements = function () {
  42440. if (!this.dataBuffer || this.dataElements) {
  42441. return;
  42442. }
  42443. var res = new Array(this.dataElementCount);
  42444. for (var i = 0; i < this.dataElementCount; i++) {
  42445. res[i] = this.dataBuffer.allocElement();
  42446. }
  42447. this.dataElements = res;
  42448. };
  42449. InstanceDataBase.prototype.freeElements = function () {
  42450. if (!this.dataElements) {
  42451. return;
  42452. }
  42453. for (var _i = 0, _a = this.dataElements; _i < _a.length; _i++) {
  42454. var ei = _a[_i];
  42455. this.dataBuffer.freeElement(ei);
  42456. }
  42457. this.dataElements = null;
  42458. };
  42459. Object.defineProperty(InstanceDataBase.prototype, "dataElementCount", {
  42460. get: function () {
  42461. return this._dataElementCount;
  42462. },
  42463. set: function (value) {
  42464. if (value === this._dataElementCount) {
  42465. return;
  42466. }
  42467. this.arrayLengthChanged = true;
  42468. this.freeElements();
  42469. this._dataElementCount = value;
  42470. this.allocElements();
  42471. },
  42472. enumerable: true,
  42473. configurable: true
  42474. });
  42475. __decorate([
  42476. instanceData()
  42477. ], InstanceDataBase.prototype, "zBias", null);
  42478. __decorate([
  42479. instanceData()
  42480. ], InstanceDataBase.prototype, "transformX", null);
  42481. __decorate([
  42482. instanceData()
  42483. ], InstanceDataBase.prototype, "transformY", null);
  42484. __decorate([
  42485. instanceData()
  42486. ], InstanceDataBase.prototype, "opacity", null);
  42487. return InstanceDataBase;
  42488. }());
  42489. BABYLON.InstanceDataBase = InstanceDataBase;
  42490. var RenderablePrim2D = (function (_super) {
  42491. __extends(RenderablePrim2D, _super);
  42492. function RenderablePrim2D(settings) {
  42493. _super.call(this, settings);
  42494. this._transparentPrimitiveInfo = null;
  42495. }
  42496. Object.defineProperty(RenderablePrim2D.prototype, "isAlphaTest", {
  42497. get: function () {
  42498. return this._useTextureAlpha() || this._isPrimAlphaTest();
  42499. },
  42500. enumerable: true,
  42501. configurable: true
  42502. });
  42503. Object.defineProperty(RenderablePrim2D.prototype, "isTransparent", {
  42504. get: function () {
  42505. return (this._opacity < 1) || this._shouldUseAlphaFromTexture() || this._isPrimTransparent();
  42506. },
  42507. enumerable: true,
  42508. configurable: true
  42509. });
  42510. Object.defineProperty(RenderablePrim2D.prototype, "renderMode", {
  42511. get: function () {
  42512. return this._renderMode;
  42513. },
  42514. enumerable: true,
  42515. configurable: true
  42516. });
  42517. /**
  42518. * Dispose the primitive and its resources, remove it from its parent
  42519. */
  42520. RenderablePrim2D.prototype.dispose = function () {
  42521. if (!_super.prototype.dispose.call(this)) {
  42522. return false;
  42523. }
  42524. if (this.renderGroup) {
  42525. this.renderGroup._setCacheGroupDirty();
  42526. }
  42527. if (this._transparentPrimitiveInfo) {
  42528. this.renderGroup._renderableData.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  42529. this._transparentPrimitiveInfo = null;
  42530. }
  42531. if (this._instanceDataParts) {
  42532. this._cleanupInstanceDataParts();
  42533. }
  42534. if (this._modelRenderCache) {
  42535. this._modelRenderCache.dispose();
  42536. this._modelRenderCache = null;
  42537. }
  42538. if (this._instanceDataParts) {
  42539. this._instanceDataParts.forEach(function (p) {
  42540. p.freeElements();
  42541. });
  42542. this._instanceDataParts = null;
  42543. }
  42544. return true;
  42545. };
  42546. RenderablePrim2D.prototype._cleanupInstanceDataParts = function () {
  42547. var gii = null;
  42548. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42549. var part = _a[_i];
  42550. part.freeElements();
  42551. gii = part.groupInstanceInfo;
  42552. }
  42553. if (gii) {
  42554. var usedCount = 0;
  42555. if (gii.hasOpaqueData) {
  42556. var od = gii.opaqueData[0];
  42557. usedCount += od._partData.usedElementCount;
  42558. }
  42559. if (gii.hasAlphaTestData) {
  42560. var atd = gii.alphaTestData[0];
  42561. usedCount += atd._partData.usedElementCount;
  42562. }
  42563. if (gii.hasTransparentData) {
  42564. var td = gii.transparentData[0];
  42565. usedCount += td._partData.usedElementCount;
  42566. }
  42567. if (usedCount === 0 && gii.modelRenderCache != null) {
  42568. this.renderGroup._renderableData._renderGroupInstancesInfo.remove(gii.modelRenderCache.modelKey);
  42569. gii.dispose();
  42570. }
  42571. if (this._modelRenderCache) {
  42572. this._modelRenderCache.dispose();
  42573. this._modelRenderCache = null;
  42574. }
  42575. }
  42576. this._instanceDataParts = null;
  42577. };
  42578. RenderablePrim2D.prototype._prepareRenderPre = function (context) {
  42579. _super.prototype._prepareRenderPre.call(this, context);
  42580. // If the model changed and we have already an instance, we must remove this instance from the obsolete model
  42581. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty) && this._instanceDataParts) {
  42582. this._cleanupInstanceDataParts();
  42583. }
  42584. // Need to create the model?
  42585. var setupModelRenderCache = false;
  42586. if (!this._modelRenderCache || this._isFlagSet(BABYLON.SmartPropertyPrim.flagModelDirty)) {
  42587. setupModelRenderCache = this._createModelRenderCache();
  42588. }
  42589. var gii = null;
  42590. var newInstance = false;
  42591. // Need to create the instance data parts?
  42592. if (!this._instanceDataParts) {
  42593. // Yes, flag it for later, more processing will have to be done
  42594. newInstance = true;
  42595. gii = this._createModelDataParts();
  42596. }
  42597. // If the ModelRenderCache is brand new, now is the time to call the implementation's specific setup method to create the rendering resources
  42598. if (setupModelRenderCache) {
  42599. this.setupModelRenderCache(this._modelRenderCache);
  42600. }
  42601. // At this stage we have everything correctly initialized, ModelRenderCache is setup, Model Instance data are good too, they have allocated elements in the Instanced DynamicFloatArray.
  42602. // The last thing to do is check if the instanced related data must be updated because a InstanceLevel property had changed or the primitive visibility changed.
  42603. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged) || context.forceRefreshPrimitive || newInstance || (this._instanceDirtyFlags !== 0) || (this._globalTransformProcessStep !== this._globalTransformStep) || this._mustUpdateInstance()) {
  42604. this._updateInstanceDataParts(gii);
  42605. }
  42606. };
  42607. RenderablePrim2D.prototype._createModelRenderCache = function () {
  42608. var _this = this;
  42609. var setupModelRenderCache = false;
  42610. if (this._modelRenderCache) {
  42611. this._modelRenderCache.dispose();
  42612. }
  42613. this._modelRenderCache = this.owner._engineData.GetOrAddModelCache(this.modelKey, function (key) {
  42614. var mrc = _this.createModelRenderCache(key);
  42615. setupModelRenderCache = true;
  42616. return mrc;
  42617. });
  42618. this._clearFlags(BABYLON.SmartPropertyPrim.flagModelDirty);
  42619. // if this is still false it means the MRC already exists, so we add a reference to it
  42620. if (!setupModelRenderCache) {
  42621. this._modelRenderCache.addRef();
  42622. }
  42623. return setupModelRenderCache;
  42624. };
  42625. RenderablePrim2D.prototype._createModelDataParts = function () {
  42626. var _this = this;
  42627. // Create the instance data parts of the primitive and store them
  42628. var parts = this.createInstanceDataParts();
  42629. this._instanceDataParts = parts;
  42630. // Check if the ModelRenderCache for this particular instance is also brand new, initialize it if it's the case
  42631. if (!this._modelRenderCache._partData) {
  42632. this._setupModelRenderCache(parts);
  42633. }
  42634. // The Rendering resources (Effect, VB, IB, Textures) are stored in the ModelRenderCache
  42635. // But it's the RenderGroup that will store all the Instanced related data to render all the primitive it owns.
  42636. // So for a given ModelKey we getOrAdd a GroupInstanceInfo that will store all these data
  42637. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.getOrAddWithFactory(this.modelKey, function (k) {
  42638. var res = new BABYLON.GroupInstanceInfo(_this.renderGroup, _this._modelRenderCache, _this._modelRenderCache._partData.length);
  42639. for (var j = 0; j < _this._modelRenderCache._partData.length; j++) {
  42640. var part = _this._instanceDataParts[j];
  42641. res.partIndexFromId.add(part.id.toString(), j);
  42642. res.usedShaderCategories[j] = ";" + _this.getUsedShaderCategories(part).join(";") + ";";
  42643. res.strides[j] = _this._modelRenderCache._partData[j]._partDataStride;
  42644. }
  42645. return res;
  42646. });
  42647. // Get the GroupInfoDataPart corresponding to the render category of the part
  42648. var rm = 0;
  42649. var gipd = null;
  42650. if (this.isTransparent) {
  42651. gipd = gii.transparentData;
  42652. rm = BABYLON.Render2DContext.RenderModeTransparent;
  42653. }
  42654. else if (this.isAlphaTest) {
  42655. gipd = gii.alphaTestData;
  42656. rm = BABYLON.Render2DContext.RenderModeAlphaTest;
  42657. }
  42658. else {
  42659. gipd = gii.opaqueData;
  42660. rm = BABYLON.Render2DContext.RenderModeOpaque;
  42661. }
  42662. // For each instance data part of the primitive, allocate the instanced element it needs for render
  42663. for (var i = 0; i < parts.length; i++) {
  42664. var part = parts[i];
  42665. part.dataBuffer = gipd[i]._partData;
  42666. part.allocElements();
  42667. part.renderMode = rm;
  42668. part.groupInstanceInfo = gii;
  42669. }
  42670. return gii;
  42671. };
  42672. RenderablePrim2D.prototype._setupModelRenderCache = function (parts) {
  42673. var ctiArray = new Array();
  42674. this._modelRenderCache._partData = new Array();
  42675. for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
  42676. var dataPart = parts_1[_i];
  42677. var pd = new BABYLON.ModelRenderCachePartData();
  42678. this._modelRenderCache._partData.push(pd);
  42679. var cat = this.getUsedShaderCategories(dataPart);
  42680. var cti = dataPart.getClassTreeInfo();
  42681. // Make sure the instance is visible other the properties won't be set and their size/offset wont be computed
  42682. var curVisible = this.isVisible;
  42683. this.isVisible = true;
  42684. // We manually trigger refreshInstanceData for the only sake of evaluating each instance property size and offset in the instance data, this can only be made at runtime. Once it's done we have all the information to create the instance data buffer.
  42685. //console.log("Build Prop Layout for " + Tools.getClassName(this._instanceDataParts[0]));
  42686. var joinCat = ";" + cat.join(";") + ";";
  42687. pd._partJoinedUsedCategories = joinCat;
  42688. InstanceClassInfo._CurCategories = joinCat;
  42689. var obj = this.beforeRefreshForLayoutConstruction(dataPart);
  42690. if (!this.refreshInstanceDataPart(dataPart)) {
  42691. console.log("Layout construction for " + BABYLON.Tools.getClassName(this._instanceDataParts[0]) + " failed because refresh returned false");
  42692. }
  42693. this.afterRefreshForLayoutConstruction(dataPart, obj);
  42694. this.isVisible = curVisible;
  42695. var size = 0;
  42696. cti.fullContent.forEach(function (k, v) {
  42697. if (!v.category || cat.indexOf(v.category) !== -1) {
  42698. if (v.attributeName === "zBias") {
  42699. pd._zBiasOffset = v.instanceOffset.get(joinCat);
  42700. }
  42701. if (!v.size) {
  42702. console.log("ERROR: Couldn't detect the size of the Property " + v.attributeName + " from type " + BABYLON.Tools.getClassName(cti.type) + ". Property is ignored.");
  42703. }
  42704. else {
  42705. size += v.size;
  42706. }
  42707. }
  42708. });
  42709. pd._partDataStride = size;
  42710. pd._partUsedCategories = cat;
  42711. pd._partId = dataPart.id;
  42712. ctiArray.push(cti);
  42713. }
  42714. this._modelRenderCache._partsClassInfo = ctiArray;
  42715. };
  42716. RenderablePrim2D.prototype.onZOrderChanged = function () {
  42717. if (this.isTransparent && this._transparentPrimitiveInfo) {
  42718. this.renderGroup._renderableData.transparentPrimitiveZChanged(this._transparentPrimitiveInfo);
  42719. var gii = this.renderGroup._renderableData._renderGroupInstancesInfo.get(this.modelKey);
  42720. // Flag the transparentData dirty has will have to sort it again
  42721. gii.transparentOrderDirty = true;
  42722. }
  42723. };
  42724. RenderablePrim2D.prototype._mustUpdateInstance = function () {
  42725. return false;
  42726. };
  42727. RenderablePrim2D.prototype._useTextureAlpha = function () {
  42728. return false;
  42729. };
  42730. RenderablePrim2D.prototype._shouldUseAlphaFromTexture = function () {
  42731. return false;
  42732. };
  42733. RenderablePrim2D.prototype._isPrimAlphaTest = function () {
  42734. return false;
  42735. };
  42736. RenderablePrim2D.prototype._isPrimTransparent = function () {
  42737. return false;
  42738. };
  42739. RenderablePrim2D.prototype._updateInstanceDataParts = function (gii) {
  42740. // Fetch the GroupInstanceInfo if we don't already have it
  42741. var rd = this.renderGroup._renderableData;
  42742. if (!gii) {
  42743. gii = rd._renderGroupInstancesInfo.get(this.modelKey);
  42744. }
  42745. var isTransparent = this.isTransparent;
  42746. var isAlphaTest = this.isAlphaTest;
  42747. var wereTransparent = false;
  42748. // Check a render mode change
  42749. var rmChanged = false;
  42750. if (this._instanceDataParts.length > 0) {
  42751. var firstPart = this._instanceDataParts[0];
  42752. var partRM = firstPart.renderMode;
  42753. var curRM = this.renderMode;
  42754. if (partRM !== curRM) {
  42755. wereTransparent = partRM === BABYLON.Render2DContext.RenderModeTransparent;
  42756. rmChanged = true;
  42757. var gipd = void 0;
  42758. switch (curRM) {
  42759. case BABYLON.Render2DContext.RenderModeTransparent:
  42760. gipd = gii.transparentData;
  42761. break;
  42762. case BABYLON.Render2DContext.RenderModeAlphaTest:
  42763. gipd = gii.alphaTestData;
  42764. break;
  42765. default:
  42766. gipd = gii.opaqueData;
  42767. }
  42768. for (var i = 0; i < this._instanceDataParts.length; i++) {
  42769. var part = this._instanceDataParts[i];
  42770. part.freeElements();
  42771. part.dataBuffer = gipd[i]._partData;
  42772. part.renderMode = curRM;
  42773. }
  42774. }
  42775. }
  42776. // Handle changes related to ZOffset
  42777. var visChanged = this._isFlagSet(BABYLON.SmartPropertyPrim.flagVisibilityChanged);
  42778. if (isTransparent || wereTransparent) {
  42779. // Handle visibility change, which is also triggered when the primitive just got created
  42780. if (visChanged || rmChanged) {
  42781. if (this.isVisible && !wereTransparent) {
  42782. if (!this._transparentPrimitiveInfo) {
  42783. // Add the primitive to the list of transparent ones in the group that render is
  42784. this._transparentPrimitiveInfo = rd.addNewTransparentPrimitiveInfo(this, gii);
  42785. }
  42786. }
  42787. else {
  42788. if (this._transparentPrimitiveInfo) {
  42789. rd.removeTransparentPrimitiveInfo(this._transparentPrimitiveInfo);
  42790. this._transparentPrimitiveInfo = null;
  42791. }
  42792. }
  42793. gii.transparentOrderDirty = true;
  42794. }
  42795. }
  42796. var rebuildTrans = false;
  42797. // For each Instance Data part, refresh it to update the data in the DynamicFloatArray
  42798. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42799. var part = _a[_i];
  42800. var justAllocated = false;
  42801. // Check if we need to allocate data elements (hidden prim which becomes visible again)
  42802. if (!part.dataElements && (visChanged || rmChanged || this.isVisible)) {
  42803. part.allocElements();
  42804. justAllocated = true;
  42805. }
  42806. InstanceClassInfo._CurCategories = gii.usedShaderCategories[gii.partIndexFromId.get(part.id.toString())];
  42807. // Will return false if the instance should not be rendered (not visible or other any reasons)
  42808. part.arrayLengthChanged = false;
  42809. if (!this.refreshInstanceDataPart(part)) {
  42810. // Free the data element
  42811. if (part.dataElements) {
  42812. part.freeElements();
  42813. }
  42814. }
  42815. rebuildTrans = rebuildTrans || part.arrayLengthChanged || justAllocated;
  42816. }
  42817. this._instanceDirtyFlags = 0;
  42818. // Make the appropriate data dirty
  42819. if (isTransparent) {
  42820. gii.transparentDirty = true;
  42821. if (rebuildTrans) {
  42822. rd._transparentListChanged = true;
  42823. }
  42824. }
  42825. else if (isAlphaTest) {
  42826. gii.alphaTestDirty = true;
  42827. }
  42828. else {
  42829. gii.opaqueDirty = true;
  42830. }
  42831. this._clearFlags(BABYLON.SmartPropertyPrim.flagVisibilityChanged); // Reset the flag as we've handled the case
  42832. };
  42833. RenderablePrim2D.prototype._updateTransparentSegmentIndices = function (ts) {
  42834. var minOff = BABYLON.Prim2DBase._bigInt;
  42835. var maxOff = 0;
  42836. for (var _i = 0, _a = this._instanceDataParts; _i < _a.length; _i++) {
  42837. var part = _a[_i];
  42838. if (part && part.dataElements) {
  42839. part.dataBuffer.pack();
  42840. for (var _b = 0, _c = part.dataElements; _b < _c.length; _b++) {
  42841. var el = _c[_b];
  42842. minOff = Math.min(minOff, el.offset);
  42843. maxOff = Math.max(maxOff, el.offset);
  42844. }
  42845. ts.startDataIndex = Math.min(ts.startDataIndex, minOff / part.dataBuffer.stride);
  42846. ts.endDataIndex = Math.max(ts.endDataIndex, (maxOff / part.dataBuffer.stride) + 1); // +1 for exclusive
  42847. }
  42848. }
  42849. };
  42850. // This internal method is mainly used for transparency processing
  42851. RenderablePrim2D.prototype._getNextPrimZOrder = function () {
  42852. var length = this._instanceDataParts.length;
  42853. for (var i = 0; i < length; i++) {
  42854. var part = this._instanceDataParts[i];
  42855. if (part) {
  42856. var stride = part.dataBuffer.stride;
  42857. var lastElementOffset = part.dataElements[part.dataElements.length - 1].offset;
  42858. // check if it's the last in the DFA
  42859. if (part.dataBuffer.totalElementCount * stride <= lastElementOffset) {
  42860. return null;
  42861. }
  42862. // Return the Z of the next primitive that lies in the DFA
  42863. return part.dataBuffer[lastElementOffset + stride + this.modelRenderCache._partData[i]._zBiasOffset];
  42864. }
  42865. }
  42866. return null;
  42867. };
  42868. // This internal method is mainly used for transparency processing
  42869. RenderablePrim2D.prototype._getPrevPrimZOrder = function () {
  42870. var length = this._instanceDataParts.length;
  42871. for (var i = 0; i < length; i++) {
  42872. var part = this._instanceDataParts[i];
  42873. if (part) {
  42874. var stride = part.dataBuffer.stride;
  42875. var firstElementOffset = part.dataElements[0].offset;
  42876. // check if it's the first in the DFA
  42877. if (firstElementOffset === 0) {
  42878. return null;
  42879. }
  42880. // Return the Z of the previous primitive that lies in the DFA
  42881. return part.dataBuffer[firstElementOffset - stride + this.modelRenderCache._partData[i]._zBiasOffset];
  42882. }
  42883. }
  42884. return null;
  42885. };
  42886. /**
  42887. * Transform a given point using the Primitive's origin setting.
  42888. * This method requires the Primitive's actualSize to be accurate
  42889. * @param p the point to transform
  42890. * @param originOffset an offset applied on the current origin before performing the transformation. Depending on which frame of reference your data is expressed you may have to apply a offset. (if you data is expressed from the bottom/left, no offset is required. If it's expressed from the center the a [-0.5;-0.5] offset has to be applied.
  42891. * @param res an allocated Vector2 that will receive the transformed content
  42892. */
  42893. RenderablePrim2D.prototype.transformPointWithOriginByRef = function (p, originOffset, res) {
  42894. var actualSize = this.actualSize;
  42895. res.x = p.x - ((this.origin.x + (originOffset ? originOffset.x : 0)) * actualSize.width);
  42896. res.y = p.y - ((this.origin.y + (originOffset ? originOffset.y : 0)) * actualSize.height);
  42897. };
  42898. RenderablePrim2D.prototype.transformPointWithOriginToRef = function (p, originOffset, res) {
  42899. this.transformPointWithOriginByRef(p, originOffset, res);
  42900. return res;
  42901. };
  42902. /**
  42903. * Get the info for a given effect based on the dataPart metadata
  42904. * @param dataPartId partId in part list to get the info
  42905. * @param vertexBufferAttributes vertex buffer attributes to manually add
  42906. * @param uniforms uniforms to manually add
  42907. * @param useInstanced specified if Instanced Array should be used, if null the engine caps will be used (so true if WebGL supports it, false otherwise), but you have the possibility to override the engine capability. However, if you manually set true but the engine does not support Instanced Array, this method will return null
  42908. */
  42909. RenderablePrim2D.prototype.getDataPartEffectInfo = function (dataPartId, vertexBufferAttributes, uniforms, useInstanced) {
  42910. if (uniforms === void 0) { uniforms = null; }
  42911. if (useInstanced === void 0) { useInstanced = null; }
  42912. var dataPart = BABYLON.Tools.first(this._instanceDataParts, function (i) { return i.id === dataPartId; });
  42913. if (!dataPart) {
  42914. return null;
  42915. }
  42916. var instancedArray = this.owner.supportInstancedArray;
  42917. if (useInstanced != null) {
  42918. // Check if the caller ask for Instanced Array and the engine does not support it, return null if it's the case
  42919. if (useInstanced && instancedArray === false) {
  42920. return null;
  42921. }
  42922. // Use the caller's setting
  42923. instancedArray = useInstanced;
  42924. }
  42925. var cti = dataPart.getClassTreeInfo();
  42926. var categories = this.getUsedShaderCategories(dataPart);
  42927. var att = cti.classContent.getShaderAttributes(categories);
  42928. var defines = "";
  42929. categories.forEach(function (c) { defines += "#define " + c + "\n"; });
  42930. if (instancedArray) {
  42931. defines += "#define Instanced\n";
  42932. }
  42933. return {
  42934. attributes: instancedArray ? vertexBufferAttributes.concat(att) : vertexBufferAttributes,
  42935. uniforms: instancedArray ? (uniforms != null ? uniforms : []) : ((uniforms != null) ? att.concat(uniforms) : (att != null ? att : [])),
  42936. defines: defines
  42937. };
  42938. };
  42939. Object.defineProperty(RenderablePrim2D.prototype, "modelRenderCache", {
  42940. get: function () {
  42941. return this._modelRenderCache;
  42942. },
  42943. enumerable: true,
  42944. configurable: true
  42945. });
  42946. RenderablePrim2D.prototype.createModelRenderCache = function (modelKey) {
  42947. return null;
  42948. };
  42949. RenderablePrim2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  42950. };
  42951. RenderablePrim2D.prototype.createInstanceDataParts = function () {
  42952. return null;
  42953. };
  42954. RenderablePrim2D.prototype.getUsedShaderCategories = function (dataPart) {
  42955. return [];
  42956. };
  42957. RenderablePrim2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  42958. };
  42959. RenderablePrim2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  42960. };
  42961. RenderablePrim2D.prototype.refreshInstanceDataPart = function (part) {
  42962. if (!this.isVisible) {
  42963. return false;
  42964. }
  42965. part.isVisible = this.isVisible;
  42966. // Which means, if there's only one data element, we're update it from this method, otherwise it is the responsibility of the derived class to call updateInstanceDataPart as many times as needed, properly (look at Text2D's implementation for more information)
  42967. if (part.dataElementCount === 1) {
  42968. part.curElement = 0;
  42969. this.updateInstanceDataPart(part);
  42970. }
  42971. return true;
  42972. };
  42973. /**
  42974. * Update the instanceDataBase level properties of a part
  42975. * @param part the part to update
  42976. * @param positionOffset to use in multi part per primitive (e.g. the Text2D has N parts for N letter to display), this give the offset to apply (e.g. the position of the letter from the bottom/left corner of the text).
  42977. */
  42978. RenderablePrim2D.prototype.updateInstanceDataPart = function (part, positionOffset) {
  42979. if (positionOffset === void 0) { positionOffset = null; }
  42980. var t = this._globalTransform.multiply(this.renderGroup.invGlobalTransform);
  42981. var size = this.renderGroup.viewportSize;
  42982. var zBias = this.actualZOffset;
  42983. var offX = 0;
  42984. var offY = 0;
  42985. // If there's an offset, apply the global transformation matrix on it to get a global offset
  42986. if (positionOffset) {
  42987. offX = positionOffset.x * t.m[0] + positionOffset.y * t.m[4];
  42988. offY = positionOffset.x * t.m[1] + positionOffset.y * t.m[5];
  42989. }
  42990. // Have to convert the coordinates to clip space which is ranged between [-1;1] on X and Y axis, with 0,0 being the left/bottom corner
  42991. // Current coordinates are expressed in renderGroup coordinates ([0, renderGroup.actualSize.width|height]) with 0,0 being at the left/top corner
  42992. // So for X:
  42993. // - tx.x = value * 2 / width: is to switch from [0, renderGroup.width] to [0, 2]
  42994. // - tx.w = (value * 2 / width) - 1: w stores the translation in renderGroup coordinates so (value * 2 / width) to switch to a clip space translation value. - 1 is to offset the overall [0;2] to [-1;1].
  42995. var w = size.width;
  42996. var h = size.height;
  42997. var invZBias = 1 / zBias;
  42998. var tx = new BABYLON.Vector4(t.m[0] * 2 / w, t.m[4] * 2 / w, 0 /*t.m[8]*/, ((t.m[12] + offX) * 2 / w) - 1);
  42999. var ty = new BABYLON.Vector4(t.m[1] * 2 / h, t.m[5] * 2 / h, 0 /*t.m[9]*/, ((t.m[13] + offY) * 2 / h) - 1);
  43000. part.transformX = tx;
  43001. part.transformY = ty;
  43002. part.opacity = this.actualOpacity;
  43003. // Stores zBias and it's inverse value because that's needed to compute the clip space W coordinate (which is 1/Z, so 1/zBias)
  43004. part.zBias = new BABYLON.Vector2(zBias, invZBias);
  43005. };
  43006. RenderablePrim2D.prototype._updateRenderMode = function () {
  43007. if (this.isTransparent) {
  43008. this._renderMode = BABYLON.Render2DContext.RenderModeTransparent;
  43009. }
  43010. else if (this.isAlphaTest) {
  43011. this._renderMode = BABYLON.Render2DContext.RenderModeAlphaTest;
  43012. }
  43013. else {
  43014. this._renderMode = BABYLON.Render2DContext.RenderModeOpaque;
  43015. }
  43016. };
  43017. RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  43018. __decorate([
  43019. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 0, function (pi) { return RenderablePrim2D.isAlphaTestProperty = pi; })
  43020. ], RenderablePrim2D.prototype, "isAlphaTest", null);
  43021. __decorate([
  43022. BABYLON.dynamicLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return RenderablePrim2D.isTransparentProperty = pi; })
  43023. ], RenderablePrim2D.prototype, "isTransparent", null);
  43024. RenderablePrim2D = __decorate([
  43025. BABYLON.className("RenderablePrim2D")
  43026. ], RenderablePrim2D);
  43027. return RenderablePrim2D;
  43028. }(BABYLON.Prim2DBase));
  43029. BABYLON.RenderablePrim2D = RenderablePrim2D;
  43030. })(BABYLON || (BABYLON = {}));
  43031. var BABYLON;
  43032. (function (BABYLON) {
  43033. var Shape2D = (function (_super) {
  43034. __extends(Shape2D, _super);
  43035. function Shape2D(settings) {
  43036. _super.call(this, settings);
  43037. if (!settings) {
  43038. settings = {};
  43039. }
  43040. var borderBrush = null;
  43041. if (settings.border) {
  43042. if (typeof (settings.border) === "string") {
  43043. borderBrush = BABYLON.Canvas2D.GetBrushFromString(settings.border);
  43044. }
  43045. else {
  43046. borderBrush = settings.border;
  43047. }
  43048. }
  43049. var fillBrush = null;
  43050. if (settings.fill) {
  43051. if (typeof (settings.fill) === "string") {
  43052. fillBrush = BABYLON.Canvas2D.GetBrushFromString(settings.fill);
  43053. }
  43054. else {
  43055. fillBrush = settings.fill;
  43056. }
  43057. }
  43058. this._isTransparent = false;
  43059. this._oldTransparent = false;
  43060. this.border = borderBrush;
  43061. this.fill = fillBrush;
  43062. this._updateTransparencyStatus();
  43063. this.borderThickness = settings.borderThickness;
  43064. }
  43065. Object.defineProperty(Shape2D.prototype, "border", {
  43066. get: function () {
  43067. return this._border;
  43068. },
  43069. set: function (value) {
  43070. this._border = value;
  43071. this._updateTransparencyStatus();
  43072. },
  43073. enumerable: true,
  43074. configurable: true
  43075. });
  43076. Object.defineProperty(Shape2D.prototype, "fill", {
  43077. /**
  43078. * Get/set the brush to render the Fill part of the Primitive
  43079. */
  43080. get: function () {
  43081. return this._fill;
  43082. },
  43083. set: function (value) {
  43084. this._fill = value;
  43085. this._updateTransparencyStatus();
  43086. },
  43087. enumerable: true,
  43088. configurable: true
  43089. });
  43090. Object.defineProperty(Shape2D.prototype, "borderThickness", {
  43091. get: function () {
  43092. return this._borderThickness;
  43093. },
  43094. set: function (value) {
  43095. this._borderThickness = value;
  43096. },
  43097. enumerable: true,
  43098. configurable: true
  43099. });
  43100. Shape2D.prototype.getUsedShaderCategories = function (dataPart) {
  43101. var cat = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  43102. // Fill Part
  43103. if (dataPart.id === Shape2D.SHAPE2D_FILLPARTID) {
  43104. var fill = this.fill;
  43105. if (fill instanceof BABYLON.SolidColorBrush2D) {
  43106. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLSOLID);
  43107. }
  43108. if (fill instanceof BABYLON.GradientColorBrush2D) {
  43109. cat.push(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT);
  43110. }
  43111. }
  43112. // Border Part
  43113. if (dataPart.id === Shape2D.SHAPE2D_BORDERPARTID) {
  43114. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDER);
  43115. var border = this.border;
  43116. if (border instanceof BABYLON.SolidColorBrush2D) {
  43117. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID);
  43118. }
  43119. if (border instanceof BABYLON.GradientColorBrush2D) {
  43120. cat.push(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT);
  43121. }
  43122. }
  43123. return cat;
  43124. };
  43125. Shape2D.prototype.refreshInstanceDataPart = function (part) {
  43126. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  43127. return false;
  43128. }
  43129. // Fill Part
  43130. if (part.id === Shape2D.SHAPE2D_FILLPARTID) {
  43131. var d = part;
  43132. if (this.fill) {
  43133. var fill = this.fill;
  43134. if (fill instanceof BABYLON.SolidColorBrush2D) {
  43135. d.fillSolidColor = fill.color;
  43136. }
  43137. else if (fill instanceof BABYLON.GradientColorBrush2D) {
  43138. d.fillGradientColor1 = fill.color1;
  43139. d.fillGradientColor2 = fill.color2;
  43140. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(fill.scale, fill.scale, fill.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), fill.rotation), new BABYLON.Vector3(fill.translation.x, fill.translation.y, 0));
  43141. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  43142. d.fillGradientTY = ty;
  43143. }
  43144. }
  43145. }
  43146. else if (part.id === Shape2D.SHAPE2D_BORDERPARTID) {
  43147. var d = part;
  43148. if (this.border) {
  43149. d.borderThickness = this.borderThickness;
  43150. var border = this.border;
  43151. if (border instanceof BABYLON.SolidColorBrush2D) {
  43152. d.borderSolidColor = border.color;
  43153. }
  43154. else if (border instanceof BABYLON.GradientColorBrush2D) {
  43155. d.borderGradientColor1 = border.color1;
  43156. d.borderGradientColor2 = border.color2;
  43157. var t = BABYLON.Matrix.Compose(new BABYLON.Vector3(border.scale, border.scale, border.scale), BABYLON.Quaternion.RotationAxis(new BABYLON.Vector3(0, 0, 1), border.rotation), new BABYLON.Vector3(border.translation.x, border.translation.y, 0));
  43158. var ty = new BABYLON.Vector4(t.m[1], t.m[5], t.m[9], t.m[13]);
  43159. d.borderGradientTY = ty;
  43160. }
  43161. }
  43162. }
  43163. return true;
  43164. };
  43165. Shape2D.prototype._updateTransparencyStatus = function () {
  43166. this._isTransparent = (this._border && this._border.isTransparent()) || (this._fill && this._fill.isTransparent()) || (this.actualOpacity < 1);
  43167. if (this._isTransparent !== this._oldTransparent) {
  43168. this._oldTransparent = this._isTransparent;
  43169. this._updateRenderMode();
  43170. }
  43171. };
  43172. Shape2D.prototype._mustUpdateInstance = function () {
  43173. var res = this._oldTransparent !== this._isTransparent;
  43174. if (res) {
  43175. this._updateRenderMode();
  43176. this._oldTransparent = this._isTransparent;
  43177. }
  43178. return res;
  43179. };
  43180. Shape2D.prototype._isPrimTransparent = function () {
  43181. return this._isTransparent;
  43182. };
  43183. Shape2D.SHAPE2D_BORDERPARTID = 1;
  43184. Shape2D.SHAPE2D_FILLPARTID = 2;
  43185. Shape2D.SHAPE2D_CATEGORY_BORDER = "Border";
  43186. Shape2D.SHAPE2D_CATEGORY_BORDERSOLID = "BorderSolid";
  43187. Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT = "BorderGradient";
  43188. Shape2D.SHAPE2D_CATEGORY_FILLSOLID = "FillSolid";
  43189. Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT = "FillGradient";
  43190. Shape2D.SHAPE2D_PROPCOUNT = BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5;
  43191. __decorate([
  43192. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Shape2D.borderProperty = pi; }, true)
  43193. ], Shape2D.prototype, "border", null);
  43194. __decorate([
  43195. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Shape2D.fillProperty = pi; }, true)
  43196. ], Shape2D.prototype, "fill", null);
  43197. __decorate([
  43198. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Shape2D.borderThicknessProperty = pi; })
  43199. ], Shape2D.prototype, "borderThickness", null);
  43200. Shape2D = __decorate([
  43201. BABYLON.className("Shape2D")
  43202. ], Shape2D);
  43203. return Shape2D;
  43204. }(BABYLON.RenderablePrim2D));
  43205. BABYLON.Shape2D = Shape2D;
  43206. var Shape2DInstanceData = (function (_super) {
  43207. __extends(Shape2DInstanceData, _super);
  43208. function Shape2DInstanceData() {
  43209. _super.apply(this, arguments);
  43210. }
  43211. Object.defineProperty(Shape2DInstanceData.prototype, "fillSolidColor", {
  43212. // FILL ATTRIBUTES
  43213. get: function () {
  43214. return null;
  43215. },
  43216. enumerable: true,
  43217. configurable: true
  43218. });
  43219. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor1", {
  43220. get: function () {
  43221. return null;
  43222. },
  43223. enumerable: true,
  43224. configurable: true
  43225. });
  43226. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientColor2", {
  43227. get: function () {
  43228. return null;
  43229. },
  43230. enumerable: true,
  43231. configurable: true
  43232. });
  43233. Object.defineProperty(Shape2DInstanceData.prototype, "fillGradientTY", {
  43234. get: function () {
  43235. return null;
  43236. },
  43237. enumerable: true,
  43238. configurable: true
  43239. });
  43240. Object.defineProperty(Shape2DInstanceData.prototype, "borderThickness", {
  43241. // BORDER ATTRIBUTES
  43242. get: function () {
  43243. return null;
  43244. },
  43245. enumerable: true,
  43246. configurable: true
  43247. });
  43248. Object.defineProperty(Shape2DInstanceData.prototype, "borderSolidColor", {
  43249. get: function () {
  43250. return null;
  43251. },
  43252. enumerable: true,
  43253. configurable: true
  43254. });
  43255. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor1", {
  43256. get: function () {
  43257. return null;
  43258. },
  43259. enumerable: true,
  43260. configurable: true
  43261. });
  43262. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientColor2", {
  43263. get: function () {
  43264. return null;
  43265. },
  43266. enumerable: true,
  43267. configurable: true
  43268. });
  43269. Object.defineProperty(Shape2DInstanceData.prototype, "borderGradientTY", {
  43270. get: function () {
  43271. return null;
  43272. },
  43273. enumerable: true,
  43274. configurable: true
  43275. });
  43276. __decorate([
  43277. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLSOLID)
  43278. ], Shape2DInstanceData.prototype, "fillSolidColor", null);
  43279. __decorate([
  43280. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43281. ], Shape2DInstanceData.prototype, "fillGradientColor1", null);
  43282. __decorate([
  43283. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43284. ], Shape2DInstanceData.prototype, "fillGradientColor2", null);
  43285. __decorate([
  43286. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  43287. ], Shape2DInstanceData.prototype, "fillGradientTY", null);
  43288. __decorate([
  43289. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDER)
  43290. ], Shape2DInstanceData.prototype, "borderThickness", null);
  43291. __decorate([
  43292. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERSOLID)
  43293. ], Shape2DInstanceData.prototype, "borderSolidColor", null);
  43294. __decorate([
  43295. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43296. ], Shape2DInstanceData.prototype, "borderGradientColor1", null);
  43297. __decorate([
  43298. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43299. ], Shape2DInstanceData.prototype, "borderGradientColor2", null);
  43300. __decorate([
  43301. BABYLON.instanceData(Shape2D.SHAPE2D_CATEGORY_BORDERGRADIENT)
  43302. ], Shape2DInstanceData.prototype, "borderGradientTY", null);
  43303. return Shape2DInstanceData;
  43304. }(BABYLON.InstanceDataBase));
  43305. BABYLON.Shape2DInstanceData = Shape2DInstanceData;
  43306. })(BABYLON || (BABYLON = {}));
  43307. var BABYLON;
  43308. (function (BABYLON) {
  43309. var Group2D = (function (_super) {
  43310. __extends(Group2D, _super);
  43311. /**
  43312. * Create an Logical or Renderable Group.
  43313. * @param settings a combination of settings, possible ones are
  43314. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  43315. * - children: an array of direct children
  43316. * - id a text identifier, for information purpose
  43317. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  43318. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  43319. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  43320. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  43321. * - zOrder: override the zOrder with the specified value
  43322. * - origin: define the normalized origin point location, default [0.5;0.5]
  43323. * - size: the size of the group. Alternatively the width and height properties can be set. If null the size will be computed from its content, default is null.
  43324. * - cacheBehavior: Define how the group should behave regarding the Canvas's cache strategy, default is Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY
  43325. * - layoutEngine: either an instance of a layout engine based class (StackPanel.Vertical, StackPanel.Horizontal) or a string ('canvas' for Canvas layout, 'StackPanel' or 'HorizontalStackPanel' for horizontal Stack Panel layout, 'VerticalStackPanel' for vertical Stack Panel layout).
  43326. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  43327. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  43328. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  43329. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  43330. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43331. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43332. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43333. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43334. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  43335. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  43336. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  43337. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  43338. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43339. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43340. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43341. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  43342. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  43343. */
  43344. function Group2D(settings) {
  43345. if (settings == null) {
  43346. settings = {};
  43347. }
  43348. if (settings.origin == null) {
  43349. settings.origin = new BABYLON.Vector2(0, 0);
  43350. }
  43351. _super.call(this, settings);
  43352. var size = (!settings.size && !settings.width && !settings.height) ? null : (settings.size || (new BABYLON.Size(settings.width || 0, settings.height || 0)));
  43353. this._trackedNode = (settings.trackNode == null) ? null : settings.trackNode;
  43354. if (this._trackedNode && this.owner) {
  43355. this.owner._registerTrackedNode(this);
  43356. }
  43357. this._cacheBehavior = (settings.cacheBehavior == null) ? Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY : settings.cacheBehavior;
  43358. this.size = size;
  43359. this._viewportPosition = BABYLON.Vector2.Zero();
  43360. }
  43361. Group2D._createCachedCanvasGroup = function (owner) {
  43362. var g = new Group2D({ parent: owner, id: "__cachedCanvasGroup__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), size: null, isVisible: true, isPickable: false });
  43363. return g;
  43364. };
  43365. Group2D.prototype.applyCachedTexture = function (vertexData, material) {
  43366. this._bindCacheTarget();
  43367. if (vertexData) {
  43368. var uv = vertexData.uvs;
  43369. var nodeuv = this._renderableData._cacheNodeUVs;
  43370. for (var i = 0; i < 4; i++) {
  43371. uv[i * 2 + 0] = nodeuv[i].x;
  43372. uv[i * 2 + 1] = nodeuv[i].y;
  43373. }
  43374. }
  43375. if (material) {
  43376. material.diffuseTexture = this._renderableData._cacheTexture;
  43377. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  43378. }
  43379. this._renderableData._cacheTexture.hasAlpha = true;
  43380. this._unbindCacheTarget();
  43381. };
  43382. Object.defineProperty(Group2D.prototype, "cachedRect", {
  43383. /**
  43384. * Allow you to access the information regarding the cached rectangle of the Group2D into the MapTexture.
  43385. * If the `noWorldSpaceNode` options was used at the creation of a WorldSpaceCanvas, the rendering of the canvas must be made by the caller, so typically you want to bind the cacheTexture property to some material/mesh and you MUST use the Group2D.cachedUVs property to get the UV coordinates to use for your quad that will display the Canvas and NOT the PackedRect.UVs property which are incorrect because the allocated surface may be bigger (due to over-provisioning or shrinking without deallocating) than what the Group is actually using.
  43386. */
  43387. get: function () {
  43388. if (!this._renderableData) {
  43389. return null;
  43390. }
  43391. return this._renderableData._cacheNode;
  43392. },
  43393. enumerable: true,
  43394. configurable: true
  43395. });
  43396. Object.defineProperty(Group2D.prototype, "cachedUVs", {
  43397. /**
  43398. * The UVs into the MapTexture that map the cached group
  43399. */
  43400. get: function () {
  43401. if (!this._renderableData) {
  43402. return null;
  43403. }
  43404. return this._renderableData._cacheNodeUVs;
  43405. },
  43406. enumerable: true,
  43407. configurable: true
  43408. });
  43409. Object.defineProperty(Group2D.prototype, "cachedUVsChanged", {
  43410. get: function () {
  43411. if (!this._renderableData) {
  43412. return null;
  43413. }
  43414. if (!this._renderableData._cacheNodeUVsChangedObservable) {
  43415. this._renderableData._cacheNodeUVsChangedObservable = new BABYLON.Observable();
  43416. }
  43417. return this._renderableData._cacheNodeUVsChangedObservable;
  43418. },
  43419. enumerable: true,
  43420. configurable: true
  43421. });
  43422. Object.defineProperty(Group2D.prototype, "cacheTexture", {
  43423. /**
  43424. * Access the texture that maintains a cached version of the Group2D.
  43425. * This is useful only if you're not using a WorldSpaceNode for your WorldSpace Canvas and therefore need to perform the rendering yourself.
  43426. */
  43427. get: function () {
  43428. if (!this._renderableData) {
  43429. return null;
  43430. }
  43431. return this._renderableData._cacheTexture;
  43432. },
  43433. enumerable: true,
  43434. configurable: true
  43435. });
  43436. /**
  43437. * Call this method to remove this Group and its children from the Canvas
  43438. */
  43439. Group2D.prototype.dispose = function () {
  43440. if (!_super.prototype.dispose.call(this)) {
  43441. return false;
  43442. }
  43443. if (this._trackedNode != null) {
  43444. this.owner._unregisterTrackedNode(this);
  43445. this._trackedNode = null;
  43446. }
  43447. if (this._renderableData) {
  43448. this._renderableData.dispose(this.owner.engine);
  43449. this._renderableData = null;
  43450. }
  43451. return true;
  43452. };
  43453. Object.defineProperty(Group2D.prototype, "isRenderableGroup", {
  43454. /**
  43455. * @returns Returns true if the Group render content, false if it's a logical group only
  43456. */
  43457. get: function () {
  43458. return this._isRenderableGroup;
  43459. },
  43460. enumerable: true,
  43461. configurable: true
  43462. });
  43463. Object.defineProperty(Group2D.prototype, "isCachedGroup", {
  43464. /**
  43465. * @returns only meaningful for isRenderableGroup, will be true if the content of the Group is cached into a texture, false if it's rendered every time
  43466. */
  43467. get: function () {
  43468. return this._isCachedGroup;
  43469. },
  43470. enumerable: true,
  43471. configurable: true
  43472. });
  43473. Object.defineProperty(Group2D.prototype, "size", {
  43474. get: function () {
  43475. return this._size;
  43476. },
  43477. /**
  43478. * Get/Set the size of the group. If null the size of the group will be determine from its content.
  43479. * BEWARE: if the Group is a RenderableGroup and its content is cache the texture will be resized each time the group is getting bigger. For performance reason the opposite won't be true: the texture won't shrink if the group does.
  43480. */
  43481. set: function (val) {
  43482. this._size = val;
  43483. },
  43484. enumerable: true,
  43485. configurable: true
  43486. });
  43487. Object.defineProperty(Group2D.prototype, "viewportSize", {
  43488. get: function () {
  43489. return this._viewportSize;
  43490. },
  43491. enumerable: true,
  43492. configurable: true
  43493. });
  43494. Object.defineProperty(Group2D.prototype, "actualSize", {
  43495. get: function () {
  43496. // The computed size will be floor on both width and height
  43497. var actualSize;
  43498. // Return the size if set by the user
  43499. if (this._size) {
  43500. actualSize = new BABYLON.Size(Math.ceil(this._size.width), Math.ceil(this._size.height));
  43501. }
  43502. else {
  43503. var m = this.boundingInfo.max();
  43504. actualSize = new BABYLON.Size(Math.ceil(m.x), Math.ceil(m.y));
  43505. }
  43506. // Compare the size with the one we previously had, if it differs we set the property dirty and trigger a GroupChanged to synchronize a displaySprite (if any)
  43507. if (!actualSize.equals(this._actualSize)) {
  43508. this.onPrimitivePropertyDirty(Group2D.actualSizeProperty.flagId);
  43509. this._actualSize = actualSize;
  43510. this.handleGroupChanged(Group2D.actualSizeProperty);
  43511. }
  43512. return actualSize;
  43513. },
  43514. enumerable: true,
  43515. configurable: true
  43516. });
  43517. Object.defineProperty(Group2D.prototype, "cacheBehavior", {
  43518. /**
  43519. * Get/set the Cache Behavior, used in case the Canvas Cache Strategy is set to CACHESTRATEGY_ALLGROUPS. Can be either GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP, GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE or GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY. See their documentation for more information.
  43520. * It is critical to understand than you HAVE TO play with this behavior in order to achieve a good performance/memory ratio. Caching all groups would certainly be the worst strategy of all.
  43521. */
  43522. get: function () {
  43523. return this._cacheBehavior;
  43524. },
  43525. enumerable: true,
  43526. configurable: true
  43527. });
  43528. Group2D.prototype._addPrimToDirtyList = function (prim) {
  43529. this._renderableData._primDirtyList.push(prim);
  43530. };
  43531. Group2D.prototype._renderCachedCanvas = function () {
  43532. this.owner._addGroupRenderCount(1);
  43533. this.updateCachedStates(true);
  43534. var context = new BABYLON.PrepareRender2DContext();
  43535. this._prepareGroupRender(context);
  43536. this._groupRender();
  43537. };
  43538. Object.defineProperty(Group2D.prototype, "trackedNode", {
  43539. /**
  43540. * Get/set the Scene's Node that should be tracked, the group's position will follow the projected position of the Node.
  43541. */
  43542. get: function () {
  43543. return this._trackedNode;
  43544. },
  43545. set: function (val) {
  43546. if (val != null) {
  43547. if (!this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  43548. this.owner._registerTrackedNode(this);
  43549. }
  43550. this._trackedNode = val;
  43551. }
  43552. else {
  43553. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  43554. this.owner._unregisterTrackedNode(this);
  43555. }
  43556. this._trackedNode = null;
  43557. }
  43558. },
  43559. enumerable: true,
  43560. configurable: true
  43561. });
  43562. Group2D.prototype.levelIntersect = function (intersectInfo) {
  43563. // If we've made it so far it means the boundingInfo intersection test succeed, the Group2D is shaped the same, so we always return true
  43564. return true;
  43565. };
  43566. Group2D.prototype.updateLevelBoundingInfo = function () {
  43567. var size;
  43568. // If the size is set by the user, the boundingInfo is computed from this value
  43569. if (this.size) {
  43570. size = this.size;
  43571. }
  43572. else {
  43573. size = new BABYLON.Size(0, 0);
  43574. }
  43575. BABYLON.BoundingInfo2D.CreateFromSizeToRef(size, this._levelBoundingInfo);
  43576. };
  43577. // Method called only on renderable groups to prepare the rendering
  43578. Group2D.prototype._prepareGroupRender = function (context) {
  43579. var sortedDirtyList = null;
  43580. // Update the Global Transformation and visibility status of the changed primitives
  43581. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  43582. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  43583. this.updateCachedStatesOf(sortedDirtyList, true);
  43584. }
  43585. // Setup the size of the rendering viewport
  43586. // In non cache mode, we're rendering directly to the rendering canvas, in this case we have to detect if the canvas size changed since the previous iteration, if it's the case all primitives must be prepared again because their transformation must be recompute
  43587. if (!this._isCachedGroup) {
  43588. // Compute the WebGL viewport's location/size
  43589. var t = this._globalTransform.getTranslation();
  43590. var s = this.actualSize.clone();
  43591. var rs = this.owner._renderingSize;
  43592. s.height = Math.min(s.height, rs.height - t.y);
  43593. s.width = Math.min(s.width, rs.width - t.x);
  43594. var x = t.x;
  43595. var y = t.y;
  43596. // The viewport where we're rendering must be the size of the canvas if this one fit in the rendering screen or clipped to the screen dimensions if needed
  43597. this._viewportPosition.x = x;
  43598. this._viewportPosition.y = y;
  43599. var vw = s.width;
  43600. var vh = s.height;
  43601. if (!this._viewportSize) {
  43602. this._viewportSize = new BABYLON.Size(vw, vh);
  43603. }
  43604. else {
  43605. if (this._viewportSize.width !== vw || this._viewportSize.height !== vh) {
  43606. context.forceRefreshPrimitive = true;
  43607. }
  43608. this._viewportSize.width = vw;
  43609. this._viewportSize.height = vh;
  43610. }
  43611. }
  43612. else {
  43613. var newSize = this.actualSize.clone();
  43614. if (!newSize.equals(this._viewportSize)) {
  43615. context.forceRefreshPrimitive = true;
  43616. }
  43617. this._viewportSize = newSize;
  43618. }
  43619. if ((this._renderableData._primDirtyList.length > 0) || context.forceRefreshPrimitive) {
  43620. // If the group is cached, set the dirty flag to true because of the incoming changes
  43621. this._cacheGroupDirty = this._isCachedGroup;
  43622. // If it's a force refresh, prepare all the children
  43623. if (context.forceRefreshPrimitive) {
  43624. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  43625. var p = _a[_i];
  43626. p._prepareRender(context);
  43627. }
  43628. }
  43629. else {
  43630. // Each primitive that changed at least once was added into the primDirtyList, we have to sort this level using
  43631. // the hierarchyDepth in order to prepare primitives from top to bottom
  43632. if (!sortedDirtyList) {
  43633. sortedDirtyList = this._renderableData._primDirtyList.sort(function (a, b) { return a.hierarchyDepth - b.hierarchyDepth; });
  43634. }
  43635. sortedDirtyList.forEach(function (p) {
  43636. // We need to check if prepare is needed because even if the primitive is in the dirtyList, its parent primitive may also have been modified, then prepared, then recurse on its children primitives (this one for instance) if the changes where impacting them.
  43637. // For instance: a Rect's position change, the position of its children primitives will also change so a prepare will be call on them. If a child was in the dirtyList we will avoid a second prepare by making this check.
  43638. if (!p.isDisposed && p._needPrepare()) {
  43639. p._prepareRender(context);
  43640. }
  43641. });
  43642. }
  43643. // Everything is updated, clear the dirty list
  43644. this._renderableData._primDirtyList.forEach(function (p) { return p._resetPropertiesDirty(); });
  43645. this._renderableData._primDirtyList.splice(0);
  43646. }
  43647. // A renderable group has a list of direct children that are also renderable groups, we recurse on them to also prepare them
  43648. this._renderableData._childrenRenderableGroups.forEach(function (g) {
  43649. g._prepareGroupRender(context);
  43650. });
  43651. };
  43652. Group2D.prototype._groupRender = function () {
  43653. var _this = this;
  43654. var engine = this.owner.engine;
  43655. var failedCount = 0;
  43656. // First recurse to children render group to render them (in their cache or on screen)
  43657. for (var _i = 0, _a = this._renderableData._childrenRenderableGroups; _i < _a.length; _i++) {
  43658. var childGroup = _a[_i];
  43659. childGroup._groupRender();
  43660. }
  43661. // Render the primitives if needed: either if we don't cache the content or if the content is cached but has changed
  43662. if (!this.isCachedGroup || this._cacheGroupDirty) {
  43663. this.owner._addGroupRenderCount(1);
  43664. if (this.isCachedGroup) {
  43665. this._bindCacheTarget();
  43666. }
  43667. else {
  43668. var curVP = engine.setDirectViewport(this._viewportPosition.x, this._viewportPosition.y, this._viewportSize.width, this._viewportSize.height);
  43669. }
  43670. var curAlphaTest = engine.getAlphaTesting() === true;
  43671. var curDepthWrite = engine.getDepthWrite() === true;
  43672. // ===================================================================
  43673. // First pass, update the InstancedArray and render Opaque primitives
  43674. // Disable Alpha Testing, Enable Depth Write
  43675. engine.setAlphaTesting(false);
  43676. engine.setDepthWrite(true);
  43677. // For each different model of primitive to render
  43678. var context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeOpaque);
  43679. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  43680. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  43681. var renderCount = _this._prepareContext(engine, context_1, v);
  43682. // If null is returned, there's no opaque data to render
  43683. if (renderCount === null) {
  43684. return;
  43685. }
  43686. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  43687. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  43688. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  43689. var renderFailed = !v.modelRenderCache.render(v, context_1);
  43690. // Update dirty flag/related
  43691. v.opaqueDirty = renderFailed;
  43692. failedCount += renderFailed ? 1 : 0;
  43693. }
  43694. });
  43695. // =======================================================================
  43696. // Second pass, update the InstancedArray and render AlphaTest primitives
  43697. // Enable Alpha Testing, Enable Depth Write
  43698. engine.setAlphaTesting(true);
  43699. engine.setDepthWrite(true);
  43700. // For each different model of primitive to render
  43701. context_1 = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeAlphaTest);
  43702. this._renderableData._renderGroupInstancesInfo.forEach(function (k, v) {
  43703. // Prepare the context object, update the WebGL Instanced Array buffer if needed
  43704. var renderCount = _this._prepareContext(engine, context_1, v);
  43705. // If null is returned, there's no opaque data to render
  43706. if (renderCount === null) {
  43707. return;
  43708. }
  43709. // Submit render only if we have something to render (everything may be hidden and the floatarray empty)
  43710. if (!_this.owner.supportInstancedArray || renderCount > 0) {
  43711. // render all the instances of this model, if the render method returns true then our instances are no longer dirty
  43712. var renderFailed = !v.modelRenderCache.render(v, context_1);
  43713. // Update dirty flag/related
  43714. v.opaqueDirty = renderFailed;
  43715. failedCount += renderFailed ? 1 : 0;
  43716. }
  43717. });
  43718. // =======================================================================
  43719. // Third pass, transparent primitive rendering
  43720. // Enable Alpha Testing, Disable Depth Write
  43721. engine.setAlphaTesting(true);
  43722. engine.setDepthWrite(false);
  43723. // First Check if the transparent List change so we can update the TransparentSegment and PartData (sort if needed)
  43724. if (this._renderableData._transparentListChanged) {
  43725. this._updateTransparentData();
  43726. }
  43727. // From this point on we have up to date data to render, so let's go
  43728. failedCount += this._renderTransparentData();
  43729. // =======================================================================
  43730. // Unbind target/restore viewport setting, clear dirty flag, and quit
  43731. // The group's content is no longer dirty
  43732. this._cacheGroupDirty = failedCount !== 0;
  43733. if (this.isCachedGroup) {
  43734. this._unbindCacheTarget();
  43735. }
  43736. else {
  43737. if (curVP) {
  43738. engine.setViewport(curVP);
  43739. }
  43740. }
  43741. // Restore saved states
  43742. engine.setAlphaTesting(curAlphaTest);
  43743. engine.setDepthWrite(curDepthWrite);
  43744. }
  43745. };
  43746. Group2D.prototype._setCacheGroupDirty = function () {
  43747. this._cacheGroupDirty = true;
  43748. };
  43749. Group2D.prototype._updateTransparentData = function () {
  43750. this.owner._addUpdateTransparentDataCount(1);
  43751. var rd = this._renderableData;
  43752. // Sort all the primitive from their depth, max (bottom) to min (top)
  43753. rd._transparentPrimitives.sort(function (a, b) { return b._primitive.actualZOffset - a._primitive.actualZOffset; });
  43754. var checkAndAddPrimInSegment = function (seg, tpiI) {
  43755. var tpi = rd._transparentPrimitives[tpiI];
  43756. // Fast rejection: if gii are different
  43757. if (seg.groupInsanceInfo !== tpi._groupInstanceInfo) {
  43758. return false;
  43759. }
  43760. //let tpiZ = tpi._primitive.actualZOffset;
  43761. // We've made it so far, the tpi can be part of the segment, add it
  43762. tpi._transparentSegment = seg;
  43763. tpi._primitive._updateTransparentSegmentIndices(seg);
  43764. return true;
  43765. };
  43766. // Free the existing TransparentSegments
  43767. for (var _i = 0, _a = rd._transparentSegments; _i < _a.length; _i++) {
  43768. var ts = _a[_i];
  43769. ts.dispose(this.owner.engine);
  43770. }
  43771. rd._transparentSegments.splice(0);
  43772. var prevSeg = null;
  43773. for (var tpiI = 0; tpiI < rd._transparentPrimitives.length; tpiI++) {
  43774. var tpi = rd._transparentPrimitives[tpiI];
  43775. // Check if the Data in which the primitive is stored is not sorted properly
  43776. if (tpi._groupInstanceInfo.transparentOrderDirty) {
  43777. tpi._groupInstanceInfo.sortTransparentData();
  43778. }
  43779. // Reset the segment, we have to create/rebuild it
  43780. tpi._transparentSegment = null;
  43781. // If there's a previous valid segment, check if this prim can be part of it
  43782. if (prevSeg) {
  43783. checkAndAddPrimInSegment(prevSeg, tpiI);
  43784. }
  43785. // If we couldn't insert in the adjacent segments, he have to create one
  43786. if (!tpi._transparentSegment) {
  43787. var ts = new BABYLON.TransparentSegment();
  43788. ts.groupInsanceInfo = tpi._groupInstanceInfo;
  43789. var prim = tpi._primitive;
  43790. ts.startZ = prim.actualZOffset;
  43791. prim._updateTransparentSegmentIndices(ts);
  43792. ts.endZ = ts.startZ;
  43793. tpi._transparentSegment = ts;
  43794. rd._transparentSegments.push(ts);
  43795. }
  43796. // Update prevSeg
  43797. prevSeg = tpi._transparentSegment;
  43798. }
  43799. //rd._firstChangedPrim = null;
  43800. rd._transparentListChanged = false;
  43801. };
  43802. Group2D.prototype._renderTransparentData = function () {
  43803. var failedCount = 0;
  43804. var context = new BABYLON.Render2DContext(BABYLON.Render2DContext.RenderModeTransparent);
  43805. var rd = this._renderableData;
  43806. var useInstanced = this.owner.supportInstancedArray;
  43807. var length = rd._transparentSegments.length;
  43808. for (var i = 0; i < length; i++) {
  43809. context.instancedBuffers = null;
  43810. var ts = rd._transparentSegments[i];
  43811. var gii = ts.groupInsanceInfo;
  43812. var mrc = gii.modelRenderCache;
  43813. var engine = this.owner.engine;
  43814. var count = ts.endDataIndex - ts.startDataIndex;
  43815. // Use Instanced Array if it's supported and if there's at least 5 prims to draw.
  43816. // We don't want to create an Instanced Buffer for less that 5 prims
  43817. if (useInstanced && count >= 5) {
  43818. if (!ts.partBuffers) {
  43819. var buffers = new Array();
  43820. for (var j = 0; j < gii.transparentData.length; j++) {
  43821. var gitd = gii.transparentData[j];
  43822. var dfa = gitd._partData;
  43823. var data = dfa.pack();
  43824. var stride = dfa.stride;
  43825. var neededSize = count * stride * 4;
  43826. var buffer = engine.createInstancesBuffer(neededSize); // Create + bind
  43827. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  43828. engine.updateArrayBuffer(segData);
  43829. buffers.push(buffer);
  43830. }
  43831. ts.partBuffers = buffers;
  43832. }
  43833. else if (gii.transparentDirty) {
  43834. for (var j = 0; j < gii.transparentData.length; j++) {
  43835. var gitd = gii.transparentData[j];
  43836. var dfa = gitd._partData;
  43837. var data = dfa.pack();
  43838. var stride = dfa.stride;
  43839. var buffer = ts.partBuffers[j];
  43840. var segData = data.subarray(ts.startDataIndex * stride, ts.endDataIndex * stride);
  43841. engine.bindArrayBuffer(buffer);
  43842. engine.updateArrayBuffer(segData);
  43843. }
  43844. }
  43845. context.useInstancing = true;
  43846. context.instancesCount = count;
  43847. context.instancedBuffers = ts.partBuffers;
  43848. context.groupInfoPartData = gii.transparentData;
  43849. var renderFailed = !mrc.render(gii, context);
  43850. failedCount += renderFailed ? 1 : 0;
  43851. }
  43852. else {
  43853. context.useInstancing = false;
  43854. context.partDataStartIndex = ts.startDataIndex;
  43855. context.partDataEndIndex = ts.endDataIndex;
  43856. context.groupInfoPartData = gii.transparentData;
  43857. var renderFailed = !mrc.render(gii, context);
  43858. failedCount += renderFailed ? 1 : 0;
  43859. }
  43860. }
  43861. return failedCount;
  43862. };
  43863. Group2D.prototype._prepareContext = function (engine, context, gii) {
  43864. var gipd = null;
  43865. var setDirty;
  43866. var getDirty;
  43867. // Render Mode specifics
  43868. switch (context.renderMode) {
  43869. case BABYLON.Render2DContext.RenderModeOpaque:
  43870. {
  43871. if (!gii.hasOpaqueData) {
  43872. return null;
  43873. }
  43874. setDirty = function (dirty) { gii.opaqueDirty = dirty; };
  43875. getDirty = function () { return gii.opaqueDirty; };
  43876. context.groupInfoPartData = gii.opaqueData;
  43877. gipd = gii.opaqueData;
  43878. break;
  43879. }
  43880. case BABYLON.Render2DContext.RenderModeAlphaTest:
  43881. {
  43882. if (!gii.hasAlphaTestData) {
  43883. return null;
  43884. }
  43885. setDirty = function (dirty) { gii.alphaTestDirty = dirty; };
  43886. getDirty = function () { return gii.alphaTestDirty; };
  43887. context.groupInfoPartData = gii.alphaTestData;
  43888. gipd = gii.alphaTestData;
  43889. break;
  43890. }
  43891. default:
  43892. throw new Error("_prepareContext is only for opaque or alphaTest");
  43893. }
  43894. var renderCount = 0;
  43895. // This part will pack the dynamicfloatarray and update the instanced array WebGLBufffer
  43896. // Skip it if instanced arrays are not supported
  43897. if (this.owner.supportInstancedArray) {
  43898. // Flag for instancing
  43899. context.useInstancing = true;
  43900. // Make sure all the WebGLBuffers of the Instanced Array are created/up to date for the parts to render.
  43901. for (var i = 0; i < gipd.length; i++) {
  43902. var pid = gipd[i];
  43903. // If the instances of the model was changed, pack the data
  43904. var array = pid._partData;
  43905. var instanceData_1 = array.pack();
  43906. renderCount += array.usedElementCount;
  43907. // Compute the size the instance buffer should have
  43908. var neededSize = array.usedElementCount * array.stride * 4;
  43909. // Check if we have to (re)create the instancesBuffer because there's none or the size is too small
  43910. if (!pid._partBuffer || (pid._partBufferSize < neededSize)) {
  43911. if (pid._partBuffer) {
  43912. engine.deleteInstancesBuffer(pid._partBuffer);
  43913. }
  43914. pid._partBuffer = engine.createInstancesBuffer(neededSize); // Create + bind
  43915. pid._partBufferSize = neededSize;
  43916. setDirty(false);
  43917. // Update the WebGL buffer to match the new content of the instances data
  43918. engine.updateArrayBuffer(instanceData_1);
  43919. }
  43920. else if (getDirty()) {
  43921. // Update the WebGL buffer to match the new content of the instances data
  43922. engine.bindArrayBuffer(pid._partBuffer);
  43923. engine.updateArrayBuffer(instanceData_1);
  43924. }
  43925. }
  43926. setDirty(false);
  43927. }
  43928. else {
  43929. context.partDataStartIndex = 0;
  43930. // Find the first valid object to get the count
  43931. if (context.groupInfoPartData.length > 0) {
  43932. var i = 0;
  43933. while (!context.groupInfoPartData[i]) {
  43934. i++;
  43935. }
  43936. context.partDataEndIndex = context.groupInfoPartData[i]._partData.usedElementCount;
  43937. }
  43938. }
  43939. return renderCount;
  43940. };
  43941. Group2D.prototype._setRenderingScale = function (scale) {
  43942. if (this._renderableData._renderingScale === scale) {
  43943. return;
  43944. }
  43945. this._renderableData._renderingScale = scale;
  43946. };
  43947. Group2D.prototype._bindCacheTarget = function () {
  43948. var curWidth;
  43949. var curHeight;
  43950. var rd = this._renderableData;
  43951. var rs = rd._renderingScale;
  43952. Group2D._s.width = Math.ceil(this.actualSize.width * rs);
  43953. Group2D._s.height = Math.ceil(this.actualSize.height * rs);
  43954. var sizeChanged = !Group2D._s.equals(rd._cacheSize);
  43955. if (rd._cacheNode) {
  43956. var size = rd._cacheNode.contentSize;
  43957. // Check if we have to deallocate because the size is too small
  43958. if ((size.width < Group2D._s.width) || (size.height < Group2D._s.height)) {
  43959. // For Screen space: over-provisioning of 7% more to avoid frequent resizing for few pixels...
  43960. // For World space: no over-provisioning
  43961. var overprovisioning = this.owner.isScreenSpace ? 1.07 : 1;
  43962. curWidth = Math.floor(Group2D._s.width * overprovisioning);
  43963. curHeight = Math.floor(Group2D._s.height * overprovisioning);
  43964. //console.log(`[${this._globalTransformProcessStep}] Resize group ${this.id}, width: ${curWidth}, height: ${curHeight}`);
  43965. rd._cacheTexture.freeRect(rd._cacheNode);
  43966. rd._cacheNode = null;
  43967. }
  43968. }
  43969. if (!rd._cacheNode) {
  43970. // Check if we have to allocate a rendering zone in the global cache texture
  43971. var res = this.owner._allocateGroupCache(this, this.parent && this.parent.renderGroup, curWidth ? new BABYLON.Size(curWidth, curHeight) : null, rd._useMipMap, rd._anisotropicLevel);
  43972. rd._cacheNode = res.node;
  43973. rd._cacheTexture = res.texture;
  43974. rd._cacheRenderSprite = res.sprite;
  43975. sizeChanged = true;
  43976. }
  43977. if (sizeChanged) {
  43978. rd._cacheSize.copyFrom(Group2D._s);
  43979. rd._cacheNodeUVs = rd._cacheNode.getUVsForCustomSize(rd._cacheSize);
  43980. this.scale = this._renderableData._renderingScale;
  43981. if (rd._cacheNodeUVsChangedObservable && rd._cacheNodeUVsChangedObservable.hasObservers()) {
  43982. rd._cacheNodeUVsChangedObservable.notifyObservers(rd._cacheNodeUVs);
  43983. }
  43984. this._setFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  43985. }
  43986. var n = rd._cacheNode;
  43987. rd._cacheTexture.bindTextureForPosSize(n.pos, Group2D._s, true);
  43988. };
  43989. Group2D.prototype._unbindCacheTarget = function () {
  43990. if (this._renderableData._cacheTexture) {
  43991. this._renderableData._cacheTexture.unbindTexture();
  43992. }
  43993. };
  43994. Group2D.prototype.handleGroupChanged = function (prop) {
  43995. // This method is only for cachedGroup
  43996. var rd = this._renderableData;
  43997. if (!rd) {
  43998. return;
  43999. }
  44000. var cachedSprite = rd._cacheRenderSprite;
  44001. if (!this.isCachedGroup || !cachedSprite) {
  44002. return;
  44003. }
  44004. // For now we only support these property changes
  44005. // TODO: add more! :)
  44006. if (prop.id === BABYLON.Prim2DBase.actualPositionProperty.id) {
  44007. cachedSprite.actualPosition = this.actualPosition.clone();
  44008. if (cachedSprite.position != null) {
  44009. cachedSprite.position = cachedSprite.actualPosition.clone();
  44010. }
  44011. }
  44012. else if (prop.id === BABYLON.Prim2DBase.rotationProperty.id) {
  44013. cachedSprite.rotation = this.rotation;
  44014. }
  44015. else if (prop.id === BABYLON.Prim2DBase.scaleProperty.id) {
  44016. cachedSprite.scale = this.scale;
  44017. }
  44018. else if (prop.id === BABYLON.Prim2DBase.originProperty.id) {
  44019. cachedSprite.origin = this.origin.clone();
  44020. }
  44021. else if (prop.id === Group2D.actualSizeProperty.id) {
  44022. cachedSprite.size = this.actualSize.clone();
  44023. }
  44024. };
  44025. Group2D.prototype.detectGroupStates = function () {
  44026. var isCanvas = this instanceof BABYLON.Canvas2D;
  44027. var canvasStrat = this.owner.cachingStrategy;
  44028. // In Don't Cache mode, only the canvas is renderable, all the other groups are logical. There are not a single cached group.
  44029. if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_DONTCACHE) {
  44030. this._isRenderableGroup = isCanvas;
  44031. this._isCachedGroup = false;
  44032. }
  44033. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_CANVAS) {
  44034. if (isCanvas) {
  44035. this._isRenderableGroup = true;
  44036. this._isCachedGroup = true;
  44037. }
  44038. else {
  44039. this._isRenderableGroup = this.id === "__cachedCanvasGroup__";
  44040. this._isCachedGroup = false;
  44041. }
  44042. }
  44043. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  44044. if (isCanvas) {
  44045. this._isRenderableGroup = true;
  44046. this._isCachedGroup = false;
  44047. }
  44048. else {
  44049. if (this.hierarchyDepth === 1) {
  44050. this._isRenderableGroup = true;
  44051. this._isCachedGroup = true;
  44052. }
  44053. else {
  44054. this._isRenderableGroup = false;
  44055. this._isCachedGroup = false;
  44056. }
  44057. }
  44058. }
  44059. else if (canvasStrat === BABYLON.Canvas2D.CACHESTRATEGY_ALLGROUPS) {
  44060. var gcb = this.cacheBehavior;
  44061. if ((gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE) || (gcb === Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP)) {
  44062. this._isRenderableGroup = gcb === Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE;
  44063. this._isCachedGroup = false;
  44064. }
  44065. if (gcb === Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY) {
  44066. this._isRenderableGroup = true;
  44067. this._isCachedGroup = true;
  44068. }
  44069. }
  44070. if (this._isRenderableGroup) {
  44071. // Yes, we do need that check, trust me, unfortunately we can call _detectGroupStates many time on the same object...
  44072. if (!this._renderableData) {
  44073. this._renderableData = new RenderableGroupData();
  44074. }
  44075. }
  44076. // If the group is tagged as renderable we add it to the renderable tree
  44077. if (this._isCachedGroup) {
  44078. var cur = this.parent;
  44079. while (cur) {
  44080. if (cur instanceof Group2D && cur._isRenderableGroup) {
  44081. if (cur._renderableData._childrenRenderableGroups.indexOf(this) === -1) {
  44082. cur._renderableData._childrenRenderableGroups.push(this);
  44083. }
  44084. break;
  44085. }
  44086. cur = cur.parent;
  44087. }
  44088. }
  44089. };
  44090. Group2D.GROUP2D_PROPCOUNT = BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 5;
  44091. /**
  44092. * Default behavior, the group will use the caching strategy defined at the Canvas Level
  44093. */
  44094. Group2D.GROUPCACHEBEHAVIOR_FOLLOWCACHESTRATEGY = 0;
  44095. /**
  44096. * When used, this group's content won't be cached, no matter which strategy used.
  44097. * If the group is part of a WorldSpace Canvas, its content will be drawn in the Canvas cache bitmap.
  44098. */
  44099. Group2D.GROUPCACHEBEHAVIOR_DONTCACHEOVERRIDE = 1;
  44100. /**
  44101. * When used, the group's content will be cached in the nearest cached parent group/canvas
  44102. */
  44103. Group2D.GROUPCACHEBEHAVIOR_CACHEINPARENTGROUP = 2;
  44104. Group2D._s = BABYLON.Size.Zero();
  44105. __decorate([
  44106. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 1, function (pi) { return Group2D.sizeProperty = pi; }, false, true)
  44107. ], Group2D.prototype, "size", null);
  44108. __decorate([
  44109. BABYLON.instanceLevelProperty(BABYLON.Prim2DBase.PRIM2DBASE_PROPCOUNT + 2, function (pi) { return Group2D.actualSizeProperty = pi; })
  44110. ], Group2D.prototype, "actualSize", null);
  44111. Group2D = __decorate([
  44112. BABYLON.className("Group2D")
  44113. ], Group2D);
  44114. return Group2D;
  44115. }(BABYLON.Prim2DBase));
  44116. BABYLON.Group2D = Group2D;
  44117. var RenderableGroupData = (function () {
  44118. function RenderableGroupData() {
  44119. this._primDirtyList = new Array();
  44120. this._childrenRenderableGroups = new Array();
  44121. this._renderGroupInstancesInfo = new BABYLON.StringDictionary();
  44122. this._transparentPrimitives = new Array();
  44123. this._transparentSegments = new Array();
  44124. this._transparentListChanged = false;
  44125. this._cacheNode = null;
  44126. this._cacheTexture = null;
  44127. this._cacheRenderSprite = null;
  44128. this._renderingScale = 1;
  44129. this._cacheNodeUVs = null;
  44130. this._cacheNodeUVsChangedObservable = null;
  44131. this._cacheSize = BABYLON.Size.Zero();
  44132. this._useMipMap = false;
  44133. this._anisotropicLevel = 1;
  44134. }
  44135. RenderableGroupData.prototype.dispose = function (engine) {
  44136. if (this._cacheRenderSprite) {
  44137. this._cacheRenderSprite.dispose();
  44138. this._cacheRenderSprite = null;
  44139. }
  44140. if (this._cacheTexture && this._cacheNode) {
  44141. this._cacheTexture.freeRect(this._cacheNode);
  44142. this._cacheTexture = null;
  44143. this._cacheNode = null;
  44144. }
  44145. if (this._primDirtyList) {
  44146. this._primDirtyList.splice(0);
  44147. this._primDirtyList = null;
  44148. }
  44149. if (this._renderGroupInstancesInfo) {
  44150. this._renderGroupInstancesInfo.forEach(function (k, v) {
  44151. v.dispose();
  44152. });
  44153. this._renderGroupInstancesInfo = null;
  44154. }
  44155. if (this._cacheNodeUVsChangedObservable) {
  44156. this._cacheNodeUVsChangedObservable.clear();
  44157. this._cacheNodeUVsChangedObservable = null;
  44158. }
  44159. if (this._transparentSegments) {
  44160. for (var _i = 0, _a = this._transparentSegments; _i < _a.length; _i++) {
  44161. var ts = _a[_i];
  44162. ts.dispose(engine);
  44163. }
  44164. this._transparentSegments.splice(0);
  44165. this._transparentSegments = null;
  44166. }
  44167. };
  44168. RenderableGroupData.prototype.addNewTransparentPrimitiveInfo = function (prim, gii) {
  44169. var tpi = new TransparentPrimitiveInfo();
  44170. tpi._primitive = prim;
  44171. tpi._groupInstanceInfo = gii;
  44172. tpi._transparentSegment = null;
  44173. this._transparentPrimitives.push(tpi);
  44174. this._transparentListChanged = true;
  44175. return tpi;
  44176. };
  44177. RenderableGroupData.prototype.removeTransparentPrimitiveInfo = function (tpi) {
  44178. var index = this._transparentPrimitives.indexOf(tpi);
  44179. if (index !== -1) {
  44180. this._transparentPrimitives.splice(index, 1);
  44181. this._transparentListChanged = true;
  44182. }
  44183. };
  44184. RenderableGroupData.prototype.transparentPrimitiveZChanged = function (tpi) {
  44185. this._transparentListChanged = true;
  44186. //this.updateSmallestZChangedPrim(tpi);
  44187. };
  44188. return RenderableGroupData;
  44189. }());
  44190. BABYLON.RenderableGroupData = RenderableGroupData;
  44191. var TransparentPrimitiveInfo = (function () {
  44192. function TransparentPrimitiveInfo() {
  44193. }
  44194. return TransparentPrimitiveInfo;
  44195. }());
  44196. BABYLON.TransparentPrimitiveInfo = TransparentPrimitiveInfo;
  44197. })(BABYLON || (BABYLON = {}));
  44198. var BABYLON;
  44199. (function (BABYLON) {
  44200. var Rectangle2DRenderCache = (function (_super) {
  44201. __extends(Rectangle2DRenderCache, _super);
  44202. function Rectangle2DRenderCache(engine, modelKey) {
  44203. _super.call(this, engine, modelKey);
  44204. this.effectsReady = false;
  44205. this.fillVB = null;
  44206. this.fillIB = null;
  44207. this.fillIndicesCount = 0;
  44208. this.instancingFillAttributes = null;
  44209. this.effectFill = null;
  44210. this.effectFillInstanced = null;
  44211. this.borderVB = null;
  44212. this.borderIB = null;
  44213. this.borderIndicesCount = 0;
  44214. this.instancingBorderAttributes = null;
  44215. this.effectBorder = null;
  44216. this.effectBorderInstanced = null;
  44217. }
  44218. Rectangle2DRenderCache.prototype.render = function (instanceInfo, context) {
  44219. // Do nothing if the shader is still loading/preparing
  44220. if (!this.effectsReady) {
  44221. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44222. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44223. return false;
  44224. }
  44225. this.effectsReady = true;
  44226. }
  44227. var canvas = instanceInfo.owner.owner;
  44228. var engine = canvas.engine;
  44229. var depthFunction = 0;
  44230. if (this.effectFill && this.effectBorder) {
  44231. depthFunction = engine.getDepthFunction();
  44232. engine.setDepthFunctionToLessOrEqual();
  44233. }
  44234. var curAlphaMode = engine.getAlphaMode();
  44235. if (this.effectFill) {
  44236. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44237. var pid = context.groupInfoPartData[partIndex];
  44238. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44239. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44240. }
  44241. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44242. engine.enableEffect(effect);
  44243. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  44244. if (context.useInstancing) {
  44245. if (!this.instancingFillAttributes) {
  44246. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44247. }
  44248. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44249. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44250. canvas._addDrawCallCount(1, context.renderMode);
  44251. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44252. engine.draw(true, 0, this.fillIndicesCount, count);
  44253. engine.unbindInstanceAttributes();
  44254. }
  44255. else {
  44256. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44257. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44258. this.setupUniforms(effect, partIndex, pid._partData, i);
  44259. engine.draw(true, 0, this.fillIndicesCount);
  44260. }
  44261. }
  44262. }
  44263. if (this.effectBorder) {
  44264. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44265. var pid = context.groupInfoPartData[partIndex];
  44266. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44267. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44268. }
  44269. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44270. engine.enableEffect(effect);
  44271. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  44272. if (context.useInstancing) {
  44273. if (!this.instancingBorderAttributes) {
  44274. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44275. }
  44276. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44277. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44278. canvas._addDrawCallCount(1, context.renderMode);
  44279. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44280. engine.draw(true, 0, this.borderIndicesCount, count);
  44281. engine.unbindInstanceAttributes();
  44282. }
  44283. else {
  44284. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44285. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44286. this.setupUniforms(effect, partIndex, pid._partData, i);
  44287. engine.draw(true, 0, this.borderIndicesCount);
  44288. }
  44289. }
  44290. }
  44291. engine.setAlphaMode(curAlphaMode, true);
  44292. if (this.effectFill && this.effectBorder) {
  44293. engine.setDepthFunction(depthFunction);
  44294. }
  44295. return true;
  44296. };
  44297. Rectangle2DRenderCache.prototype.dispose = function () {
  44298. if (!_super.prototype.dispose.call(this)) {
  44299. return false;
  44300. }
  44301. if (this.fillVB) {
  44302. this._engine._releaseBuffer(this.fillVB);
  44303. this.fillVB = null;
  44304. }
  44305. if (this.fillIB) {
  44306. this._engine._releaseBuffer(this.fillIB);
  44307. this.fillIB = null;
  44308. }
  44309. this.effectFill = null;
  44310. this.effectFillInstanced = null;
  44311. this.effectBorder = null;
  44312. this.effectBorderInstanced = null;
  44313. if (this.borderVB) {
  44314. this._engine._releaseBuffer(this.borderVB);
  44315. this.borderVB = null;
  44316. }
  44317. if (this.borderIB) {
  44318. this._engine._releaseBuffer(this.borderIB);
  44319. this.borderIB = null;
  44320. }
  44321. return true;
  44322. };
  44323. return Rectangle2DRenderCache;
  44324. }(BABYLON.ModelRenderCache));
  44325. BABYLON.Rectangle2DRenderCache = Rectangle2DRenderCache;
  44326. var Rectangle2DInstanceData = (function (_super) {
  44327. __extends(Rectangle2DInstanceData, _super);
  44328. function Rectangle2DInstanceData(partId) {
  44329. _super.call(this, partId, 1);
  44330. }
  44331. Object.defineProperty(Rectangle2DInstanceData.prototype, "properties", {
  44332. get: function () {
  44333. return null;
  44334. },
  44335. enumerable: true,
  44336. configurable: true
  44337. });
  44338. __decorate([
  44339. BABYLON.instanceData()
  44340. ], Rectangle2DInstanceData.prototype, "properties", null);
  44341. return Rectangle2DInstanceData;
  44342. }(BABYLON.Shape2DInstanceData));
  44343. BABYLON.Rectangle2DInstanceData = Rectangle2DInstanceData;
  44344. var Rectangle2D = (function (_super) {
  44345. __extends(Rectangle2D, _super);
  44346. /**
  44347. * Create an Rectangle 2D Shape primitive. May be a sharp rectangle (with sharp corners), or a rounded one.
  44348. * @param settings a combination of settings, possible ones are
  44349. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  44350. * - children: an array of direct children
  44351. * - id a text identifier, for information purpose
  44352. * - position: the X & Y positions relative to its parent. Alternatively the x and y settings can be set. Default is [0;0]
  44353. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44354. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44355. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44356. * - zOrder: override the zOrder with the specified value
  44357. * - origin: define the normalized origin point location, default [0.5;0.5]
  44358. * - size: the size of the group. Alternatively the width and height settings can be set. Default will be [10;10].
  44359. * - roundRadius: if the rectangle has rounded corner, set their radius, default is 0 (to get a sharp edges rectangle).
  44360. * - fill: the brush used to draw the fill content of the rectangle, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
  44361. * - border: the brush used to draw the border of the rectangle, you can set null to draw nothing (but you will have to set a fill brush), default is null. can also be a string value (see Canvas2D.GetBrushFromString)
  44362. * - borderThickness: the thickness of the drawn border, default is 1.
  44363. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  44364. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  44365. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  44366. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  44367. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44368. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44369. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44370. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44371. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44372. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44373. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44374. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44375. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44376. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44377. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44378. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44379. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44380. */
  44381. function Rectangle2D(settings) {
  44382. // Avoid checking every time if the object exists
  44383. if (settings == null) {
  44384. settings = {};
  44385. }
  44386. _super.call(this, settings);
  44387. if (settings.size != null) {
  44388. this.size = settings.size;
  44389. }
  44390. else if (settings.width || settings.height) {
  44391. var size = new BABYLON.Size(settings.width, settings.height);
  44392. this.size = size;
  44393. }
  44394. //let size = settings.size || (new Size((settings.width === null) ? null : (settings.width || 10), (settings.height === null) ? null : (settings.height || 10)));
  44395. var roundRadius = (settings.roundRadius == null) ? 0 : settings.roundRadius;
  44396. var borderThickness = (settings.borderThickness == null) ? 1 : settings.borderThickness;
  44397. //this.size = size;
  44398. this.roundRadius = roundRadius;
  44399. this.borderThickness = borderThickness;
  44400. }
  44401. Object.defineProperty(Rectangle2D.prototype, "actualSize", {
  44402. get: function () {
  44403. if (this._actualSize) {
  44404. return this._actualSize;
  44405. }
  44406. return this.size;
  44407. },
  44408. set: function (value) {
  44409. this._actualSize = value;
  44410. },
  44411. enumerable: true,
  44412. configurable: true
  44413. });
  44414. Object.defineProperty(Rectangle2D.prototype, "notRounded", {
  44415. get: function () {
  44416. return this._notRounded;
  44417. },
  44418. set: function (value) {
  44419. this._notRounded = value;
  44420. },
  44421. enumerable: true,
  44422. configurable: true
  44423. });
  44424. Object.defineProperty(Rectangle2D.prototype, "roundRadius", {
  44425. get: function () {
  44426. return this._roundRadius;
  44427. },
  44428. set: function (value) {
  44429. this._roundRadius = value;
  44430. this.notRounded = value === 0;
  44431. this._positioningDirty();
  44432. },
  44433. enumerable: true,
  44434. configurable: true
  44435. });
  44436. Rectangle2D.prototype.levelIntersect = function (intersectInfo) {
  44437. // If we got there it mean the boundingInfo intersection succeed, if the rectangle has not roundRadius, it means it succeed!
  44438. if (this.notRounded) {
  44439. return true;
  44440. }
  44441. // If we got so far it means the bounding box at least passed, so we know it's inside the bounding rectangle, but it can be outside the roundedRectangle.
  44442. // The easiest way is to check if the point is inside on of the four corners area (a little square of roundRadius size at the four corners)
  44443. // If it's the case for one, check if the mouse is located in the quarter that we care about (the one who is visible) then finally make a distance check with the roundRadius radius to see if it's inside the circle quarter or outside.
  44444. // First let remove the origin out the equation, to have the rectangle with an origin at bottom/left
  44445. var size = this.size;
  44446. Rectangle2D._i0.x = intersectInfo._localPickPosition.x;
  44447. Rectangle2D._i0.y = intersectInfo._localPickPosition.y;
  44448. var rr = this.roundRadius;
  44449. var rrs = rr * rr;
  44450. // Check if the point is in the bottom/left quarter area
  44451. Rectangle2D._i1.x = rr;
  44452. Rectangle2D._i1.y = rr;
  44453. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  44454. // Compute the intersection point in the quarter local space
  44455. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44456. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44457. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44458. return Rectangle2D._i2.lengthSquared() <= rrs;
  44459. }
  44460. // Check if the point is in the top/left quarter area
  44461. Rectangle2D._i1.x = rr;
  44462. Rectangle2D._i1.y = size.height - rr;
  44463. if (Rectangle2D._i0.x <= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  44464. // Compute the intersection point in the quarter local space
  44465. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44466. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44467. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44468. return Rectangle2D._i2.lengthSquared() <= rrs;
  44469. }
  44470. // Check if the point is in the top/right quarter area
  44471. Rectangle2D._i1.x = size.width - rr;
  44472. Rectangle2D._i1.y = size.height - rr;
  44473. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y >= Rectangle2D._i1.y) {
  44474. // Compute the intersection point in the quarter local space
  44475. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44476. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44477. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44478. return Rectangle2D._i2.lengthSquared() <= rrs;
  44479. }
  44480. // Check if the point is in the bottom/right quarter area
  44481. Rectangle2D._i1.x = size.width - rr;
  44482. Rectangle2D._i1.y = rr;
  44483. if (Rectangle2D._i0.x >= Rectangle2D._i1.x && Rectangle2D._i0.y <= Rectangle2D._i1.y) {
  44484. // Compute the intersection point in the quarter local space
  44485. Rectangle2D._i2.x = Rectangle2D._i0.x - Rectangle2D._i1.x;
  44486. Rectangle2D._i2.y = Rectangle2D._i0.y - Rectangle2D._i1.y;
  44487. // It's a hit if the squared distance is less/equal to the squared radius of the round circle
  44488. return Rectangle2D._i2.lengthSquared() <= rrs;
  44489. }
  44490. // At any other locations the point is guarantied to be inside
  44491. return true;
  44492. };
  44493. Rectangle2D.prototype.updateLevelBoundingInfo = function () {
  44494. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44495. };
  44496. Rectangle2D.prototype.createModelRenderCache = function (modelKey) {
  44497. var renderCache = new Rectangle2DRenderCache(this.owner.engine, modelKey);
  44498. return renderCache;
  44499. };
  44500. Rectangle2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44501. var renderCache = modelRenderCache;
  44502. var engine = this.owner.engine;
  44503. // Need to create WebGL resources for fill part?
  44504. if (this.fill) {
  44505. var vbSize = ((this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4) + 1;
  44506. var vb = new Float32Array(vbSize);
  44507. for (var i = 0; i < vbSize; i++) {
  44508. vb[i] = i;
  44509. }
  44510. renderCache.fillVB = engine.createVertexBuffer(vb);
  44511. var triCount = vbSize - 1;
  44512. var ib = new Float32Array(triCount * 3);
  44513. for (var i = 0; i < triCount; i++) {
  44514. ib[i * 3 + 0] = 0;
  44515. ib[i * 3 + 2] = i + 1;
  44516. ib[i * 3 + 1] = i + 2;
  44517. }
  44518. ib[triCount * 3 - 2] = 1;
  44519. renderCache.fillIB = engine.createIndexBuffer(ib);
  44520. renderCache.fillIndicesCount = triCount * 3;
  44521. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  44522. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  44523. if (ei) {
  44524. renderCache.effectFillInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44525. }
  44526. // Get the non instanced version
  44527. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  44528. renderCache.effectFill = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44529. }
  44530. // Need to create WebGL resource for border part?
  44531. if (this.border) {
  44532. var vbSize = (this.notRounded ? 1 : Rectangle2D.roundSubdivisions) * 4 * 2;
  44533. var vb = new Float32Array(vbSize);
  44534. for (var i = 0; i < vbSize; i++) {
  44535. vb[i] = i;
  44536. }
  44537. renderCache.borderVB = engine.createVertexBuffer(vb);
  44538. var triCount = vbSize;
  44539. var rs = triCount / 2;
  44540. var ib = new Float32Array(triCount * 3);
  44541. for (var i = 0; i < rs; i++) {
  44542. var r0 = i;
  44543. var r1 = (i + 1) % rs;
  44544. ib[i * 6 + 0] = rs + r1;
  44545. ib[i * 6 + 1] = rs + r0;
  44546. ib[i * 6 + 2] = r0;
  44547. ib[i * 6 + 3] = r1;
  44548. ib[i * 6 + 4] = rs + r1;
  44549. ib[i * 6 + 5] = r0;
  44550. }
  44551. renderCache.borderIB = engine.createIndexBuffer(ib);
  44552. renderCache.borderIndicesCount = triCount * 3;
  44553. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  44554. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  44555. if (ei) {
  44556. renderCache.effectBorderInstanced = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44557. }
  44558. // Get the non instanced version
  44559. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  44560. renderCache.effectBorder = engine.createEffect("rect2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44561. }
  44562. return renderCache;
  44563. };
  44564. // We override this method because if there's a roundRadius set, we will reduce the initial Content Area to make sure the computed area won't intersect with the shape contour. The formula is simple: we shrink the incoming size by the amount of the roundRadius
  44565. Rectangle2D.prototype._getInitialContentAreaToRef = function (primSize, initialContentPosition, initialContentArea) {
  44566. // Fall back to default implementation if there's no round Radius
  44567. if (this._notRounded) {
  44568. _super.prototype._getInitialContentAreaToRef.call(this, primSize, initialContentPosition, initialContentArea);
  44569. }
  44570. else {
  44571. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  44572. initialContentPosition.x = initialContentPosition.y = rr;
  44573. initialContentArea.width = Math.max(0, primSize.width - (rr * 2));
  44574. initialContentArea.height = Math.max(0, primSize.height - (rr * 2));
  44575. }
  44576. };
  44577. Rectangle2D.prototype._getActualSizeFromContentToRef = function (primSize, newPrimSize) {
  44578. // Fall back to default implementation if there's no round Radius
  44579. if (this._notRounded) {
  44580. _super.prototype._getActualSizeFromContentToRef.call(this, primSize, newPrimSize);
  44581. }
  44582. else {
  44583. var rr = Math.round((this.roundRadius - (this.roundRadius / Math.sqrt(2))) * 1.3);
  44584. newPrimSize.copyFrom(primSize);
  44585. newPrimSize.width += rr * 2;
  44586. newPrimSize.height += rr * 2;
  44587. }
  44588. };
  44589. Rectangle2D.prototype.createInstanceDataParts = function () {
  44590. var res = new Array();
  44591. if (this.border) {
  44592. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  44593. }
  44594. if (this.fill) {
  44595. res.push(new Rectangle2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  44596. }
  44597. return res;
  44598. };
  44599. Rectangle2D.prototype.refreshInstanceDataPart = function (part) {
  44600. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44601. return false;
  44602. }
  44603. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  44604. var d = part;
  44605. var size = this.actualSize;
  44606. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  44607. }
  44608. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  44609. var d = part;
  44610. var size = this.actualSize;
  44611. d.properties = new BABYLON.Vector3(size.width, size.height, this.roundRadius || 0);
  44612. }
  44613. return true;
  44614. };
  44615. Rectangle2D._i0 = BABYLON.Vector2.Zero();
  44616. Rectangle2D._i1 = BABYLON.Vector2.Zero();
  44617. Rectangle2D._i2 = BABYLON.Vector2.Zero();
  44618. Rectangle2D.roundSubdivisions = 16;
  44619. __decorate([
  44620. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Rectangle2D.actualSizeProperty = pi; }, false, true)
  44621. ], Rectangle2D.prototype, "actualSize", null);
  44622. __decorate([
  44623. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Rectangle2D.notRoundedProperty = pi; })
  44624. ], Rectangle2D.prototype, "notRounded", null);
  44625. __decorate([
  44626. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Rectangle2D.roundRadiusProperty = pi; })
  44627. ], Rectangle2D.prototype, "roundRadius", null);
  44628. Rectangle2D = __decorate([
  44629. BABYLON.className("Rectangle2D")
  44630. ], Rectangle2D);
  44631. return Rectangle2D;
  44632. }(BABYLON.Shape2D));
  44633. BABYLON.Rectangle2D = Rectangle2D;
  44634. })(BABYLON || (BABYLON = {}));
  44635. var BABYLON;
  44636. (function (BABYLON) {
  44637. var Ellipse2DRenderCache = (function (_super) {
  44638. __extends(Ellipse2DRenderCache, _super);
  44639. function Ellipse2DRenderCache(engine, modelKey) {
  44640. _super.call(this, engine, modelKey);
  44641. this.effectsReady = false;
  44642. this.fillVB = null;
  44643. this.fillIB = null;
  44644. this.fillIndicesCount = 0;
  44645. this.instancingFillAttributes = null;
  44646. this.effectFillInstanced = null;
  44647. this.effectFill = null;
  44648. this.borderVB = null;
  44649. this.borderIB = null;
  44650. this.borderIndicesCount = 0;
  44651. this.instancingBorderAttributes = null;
  44652. this.effectBorderInstanced = null;
  44653. this.effectBorder = null;
  44654. }
  44655. Ellipse2DRenderCache.prototype.render = function (instanceInfo, context) {
  44656. // Do nothing if the shader is still loading/preparing
  44657. if (!this.effectsReady) {
  44658. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  44659. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  44660. return false;
  44661. }
  44662. this.effectsReady = true;
  44663. }
  44664. var canvas = instanceInfo.owner.owner;
  44665. var engine = canvas.engine;
  44666. var depthFunction = 0;
  44667. if (this.effectFill && this.effectBorder) {
  44668. depthFunction = engine.getDepthFunction();
  44669. engine.setDepthFunctionToLessOrEqual();
  44670. }
  44671. var curAlphaMode = engine.getAlphaMode();
  44672. if (this.effectFill) {
  44673. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  44674. var pid = context.groupInfoPartData[partIndex];
  44675. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44676. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44677. }
  44678. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  44679. engine.enableEffect(effect);
  44680. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [1], 4, effect);
  44681. if (context.useInstancing) {
  44682. if (!this.instancingFillAttributes) {
  44683. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  44684. }
  44685. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44686. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44687. canvas._addDrawCallCount(1, context.renderMode);
  44688. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  44689. engine.draw(true, 0, this.fillIndicesCount, count);
  44690. engine.unbindInstanceAttributes();
  44691. }
  44692. else {
  44693. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44694. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44695. this.setupUniforms(effect, partIndex, pid._partData, i);
  44696. engine.draw(true, 0, this.fillIndicesCount);
  44697. }
  44698. }
  44699. }
  44700. if (this.effectBorder) {
  44701. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  44702. var pid = context.groupInfoPartData[partIndex];
  44703. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  44704. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  44705. }
  44706. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  44707. engine.enableEffect(effect);
  44708. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [1], 4, effect);
  44709. if (context.useInstancing) {
  44710. if (!this.instancingBorderAttributes) {
  44711. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  44712. }
  44713. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  44714. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  44715. canvas._addDrawCallCount(1, context.renderMode);
  44716. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  44717. engine.draw(true, 0, this.borderIndicesCount, count);
  44718. engine.unbindInstanceAttributes();
  44719. }
  44720. else {
  44721. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  44722. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  44723. this.setupUniforms(effect, partIndex, pid._partData, i);
  44724. engine.draw(true, 0, this.borderIndicesCount);
  44725. }
  44726. }
  44727. }
  44728. engine.setAlphaMode(curAlphaMode, true);
  44729. if (this.effectFill && this.effectBorder) {
  44730. engine.setDepthFunction(depthFunction);
  44731. }
  44732. return true;
  44733. };
  44734. Ellipse2DRenderCache.prototype.dispose = function () {
  44735. if (!_super.prototype.dispose.call(this)) {
  44736. return false;
  44737. }
  44738. if (this.fillVB) {
  44739. this._engine._releaseBuffer(this.fillVB);
  44740. this.fillVB = null;
  44741. }
  44742. if (this.fillIB) {
  44743. this._engine._releaseBuffer(this.fillIB);
  44744. this.fillIB = null;
  44745. }
  44746. this.effectFill = null;
  44747. this.effectFillInstanced = null;
  44748. this.effectBorder = null;
  44749. this.effectBorderInstanced = null;
  44750. if (this.borderVB) {
  44751. this._engine._releaseBuffer(this.borderVB);
  44752. this.borderVB = null;
  44753. }
  44754. if (this.borderIB) {
  44755. this._engine._releaseBuffer(this.borderIB);
  44756. this.borderIB = null;
  44757. }
  44758. return true;
  44759. };
  44760. return Ellipse2DRenderCache;
  44761. }(BABYLON.ModelRenderCache));
  44762. BABYLON.Ellipse2DRenderCache = Ellipse2DRenderCache;
  44763. var Ellipse2DInstanceData = (function (_super) {
  44764. __extends(Ellipse2DInstanceData, _super);
  44765. function Ellipse2DInstanceData(partId) {
  44766. _super.call(this, partId, 1);
  44767. }
  44768. Object.defineProperty(Ellipse2DInstanceData.prototype, "properties", {
  44769. get: function () {
  44770. return null;
  44771. },
  44772. enumerable: true,
  44773. configurable: true
  44774. });
  44775. __decorate([
  44776. BABYLON.instanceData()
  44777. ], Ellipse2DInstanceData.prototype, "properties", null);
  44778. return Ellipse2DInstanceData;
  44779. }(BABYLON.Shape2DInstanceData));
  44780. BABYLON.Ellipse2DInstanceData = Ellipse2DInstanceData;
  44781. var Ellipse2D = (function (_super) {
  44782. __extends(Ellipse2D, _super);
  44783. /**
  44784. * Create an Ellipse 2D Shape primitive
  44785. * @param settings a combination of settings, possible ones are
  44786. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  44787. * - children: an array of direct children
  44788. * - id: a text identifier, for information purpose
  44789. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  44790. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  44791. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  44792. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  44793. * - zOrder: override the zOrder with the specified value
  44794. * - origin: define the normalized origin point location, default [0.5;0.5]
  44795. * - size: the size of the group. Alternatively the width and height properties can be set. Default will be [10;10].
  44796. * - subdivision: the number of subdivision to create the ellipse perimeter, default is 64.
  44797. * - fill: the brush used to draw the fill content of the ellipse, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can also be a string value (see Canvas2D.GetBrushFromString)
  44798. * - border: the brush used to draw the border of the ellipse, you can set null to draw nothing (but you will have to set a fill brush), default is null. can be a string value (see Canvas2D.GetBrushFromString)
  44799. * - borderThickness: the thickness of the drawn border, default is 1.
  44800. * - isVisible: true if the group must be visible, false for hidden. Default is true.
  44801. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  44802. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  44803. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  44804. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44805. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44806. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44807. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44808. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  44809. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  44810. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  44811. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  44812. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44813. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44814. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44815. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  44816. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  44817. */
  44818. function Ellipse2D(settings) {
  44819. // Avoid checking every time if the object exists
  44820. if (settings == null) {
  44821. settings = {};
  44822. }
  44823. _super.call(this, settings);
  44824. if (settings.size != null) {
  44825. this.size = settings.size;
  44826. }
  44827. else if (settings.width || settings.height) {
  44828. var size = new BABYLON.Size(settings.width, settings.height);
  44829. this.size = size;
  44830. }
  44831. var sub = (settings.subdivisions == null) ? 64 : settings.subdivisions;
  44832. this.subdivisions = sub;
  44833. }
  44834. Object.defineProperty(Ellipse2D.prototype, "actualSize", {
  44835. get: function () {
  44836. if (this._actualSize) {
  44837. return this._actualSize;
  44838. }
  44839. return this.size;
  44840. },
  44841. set: function (value) {
  44842. this._actualSize = value;
  44843. },
  44844. enumerable: true,
  44845. configurable: true
  44846. });
  44847. Object.defineProperty(Ellipse2D.prototype, "subdivisions", {
  44848. get: function () {
  44849. return this._subdivisions;
  44850. },
  44851. set: function (value) {
  44852. this._subdivisions = value;
  44853. },
  44854. enumerable: true,
  44855. configurable: true
  44856. });
  44857. Ellipse2D.prototype.levelIntersect = function (intersectInfo) {
  44858. var w = this.size.width / 2;
  44859. var h = this.size.height / 2;
  44860. var x = intersectInfo._localPickPosition.x - w;
  44861. var y = intersectInfo._localPickPosition.y - h;
  44862. return ((x * x) / (w * w) + (y * y) / (h * h)) <= 1;
  44863. };
  44864. Ellipse2D.prototype.updateLevelBoundingInfo = function () {
  44865. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  44866. };
  44867. Ellipse2D.prototype.createModelRenderCache = function (modelKey) {
  44868. var renderCache = new Ellipse2DRenderCache(this.owner.engine, modelKey);
  44869. return renderCache;
  44870. };
  44871. Ellipse2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  44872. var renderCache = modelRenderCache;
  44873. var engine = this.owner.engine;
  44874. // Need to create WebGL resources for fill part?
  44875. if (this.fill) {
  44876. var vbSize = this.subdivisions + 1;
  44877. var vb = new Float32Array(vbSize);
  44878. for (var i = 0; i < vbSize; i++) {
  44879. vb[i] = i;
  44880. }
  44881. renderCache.fillVB = engine.createVertexBuffer(vb);
  44882. var triCount = vbSize - 1;
  44883. var ib = new Float32Array(triCount * 3);
  44884. for (var i = 0; i < triCount; i++) {
  44885. ib[i * 3 + 0] = 0;
  44886. ib[i * 3 + 2] = i + 1;
  44887. ib[i * 3 + 1] = i + 2;
  44888. }
  44889. ib[triCount * 3 - 2] = 1;
  44890. renderCache.fillIB = engine.createIndexBuffer(ib);
  44891. renderCache.fillIndicesCount = triCount * 3;
  44892. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  44893. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, true);
  44894. if (ei) {
  44895. renderCache.effectFillInstanced = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44896. }
  44897. // Get the non instanced version
  44898. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["index"], null, false);
  44899. renderCache.effectFill = engine.createEffect({ vertex: "ellipse2d", fragment: "ellipse2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  44900. }
  44901. // Need to create WebGL resource for border part?
  44902. if (this.border) {
  44903. var vbSize = this.subdivisions * 2;
  44904. var vb = new Float32Array(vbSize);
  44905. for (var i = 0; i < vbSize; i++) {
  44906. vb[i] = i;
  44907. }
  44908. renderCache.borderVB = engine.createVertexBuffer(vb);
  44909. var triCount = vbSize;
  44910. var rs = triCount / 2;
  44911. var ib = new Float32Array(triCount * 3);
  44912. for (var i = 0; i < rs; i++) {
  44913. var r0 = i;
  44914. var r1 = (i + 1) % rs;
  44915. ib[i * 6 + 0] = rs + r1;
  44916. ib[i * 6 + 1] = rs + r0;
  44917. ib[i * 6 + 2] = r0;
  44918. ib[i * 6 + 3] = r1;
  44919. ib[i * 6 + 4] = rs + r1;
  44920. ib[i * 6 + 5] = r0;
  44921. }
  44922. renderCache.borderIB = engine.createIndexBuffer(ib);
  44923. renderCache.borderIndicesCount = (triCount * 3);
  44924. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  44925. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, true);
  44926. if (ei) {
  44927. renderCache.effectBorderInstanced = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44928. }
  44929. // Get the non instanced version
  44930. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["index"], null, false);
  44931. renderCache.effectBorder = engine.createEffect("ellipse2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  44932. }
  44933. return renderCache;
  44934. };
  44935. Ellipse2D.prototype.createInstanceDataParts = function () {
  44936. var res = new Array();
  44937. if (this.border) {
  44938. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  44939. }
  44940. if (this.fill) {
  44941. res.push(new Ellipse2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  44942. }
  44943. return res;
  44944. };
  44945. Ellipse2D.prototype.refreshInstanceDataPart = function (part) {
  44946. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  44947. return false;
  44948. }
  44949. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  44950. var d = part;
  44951. var size = this.actualSize;
  44952. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  44953. }
  44954. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  44955. var d = part;
  44956. var size = this.actualSize;
  44957. d.properties = new BABYLON.Vector3(size.width, size.height, this.subdivisions);
  44958. }
  44959. return true;
  44960. };
  44961. __decorate([
  44962. BABYLON.instanceLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Ellipse2D.acutalSizeProperty = pi; }, false, true)
  44963. ], Ellipse2D.prototype, "actualSize", null);
  44964. __decorate([
  44965. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Ellipse2D.subdivisionsProperty = pi; })
  44966. ], Ellipse2D.prototype, "subdivisions", null);
  44967. Ellipse2D = __decorate([
  44968. BABYLON.className("Ellipse2D")
  44969. ], Ellipse2D);
  44970. return Ellipse2D;
  44971. }(BABYLON.Shape2D));
  44972. BABYLON.Ellipse2D = Ellipse2D;
  44973. })(BABYLON || (BABYLON = {}));
  44974. var BABYLON;
  44975. (function (BABYLON) {
  44976. var Sprite2DRenderCache = (function (_super) {
  44977. __extends(Sprite2DRenderCache, _super);
  44978. function Sprite2DRenderCache() {
  44979. _super.apply(this, arguments);
  44980. this.effectsReady = false;
  44981. this.vb = null;
  44982. this.ib = null;
  44983. this.instancingAttributes = null;
  44984. this.texture = null;
  44985. this.effect = null;
  44986. this.effectInstanced = null;
  44987. }
  44988. Sprite2DRenderCache.prototype.render = function (instanceInfo, context) {
  44989. // Do nothing if the shader is still loading/preparing
  44990. if (!this.effectsReady) {
  44991. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  44992. return false;
  44993. }
  44994. this.effectsReady = true;
  44995. }
  44996. // Compute the offset locations of the attributes in the vertex shader that will be mapped to the instance buffer data
  44997. var canvas = instanceInfo.owner.owner;
  44998. var engine = canvas.engine;
  44999. var cur = engine.getAlphaMode();
  45000. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  45001. engine.enableEffect(effect);
  45002. effect.setTexture("diffuseSampler", this.texture);
  45003. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  45004. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45005. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45006. }
  45007. effect.setBool("alphaTest", context.renderMode === BABYLON.Render2DContext.RenderModeAlphaTest);
  45008. var pid = context.groupInfoPartData[0];
  45009. if (context.useInstancing) {
  45010. if (!this.instancingAttributes) {
  45011. this.instancingAttributes = this.loadInstancingAttributes(Sprite2D.SPRITE2D_MAINPARTID, effect);
  45012. }
  45013. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  45014. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45015. canvas._addDrawCallCount(1, context.renderMode);
  45016. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  45017. engine.draw(true, 0, 6, count);
  45018. engine.unbindInstanceAttributes();
  45019. }
  45020. else {
  45021. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45022. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45023. this.setupUniforms(effect, 0, pid._partData, i);
  45024. engine.draw(true, 0, 6);
  45025. }
  45026. }
  45027. engine.setAlphaMode(cur, true);
  45028. return true;
  45029. };
  45030. Sprite2DRenderCache.prototype.dispose = function () {
  45031. if (!_super.prototype.dispose.call(this)) {
  45032. return false;
  45033. }
  45034. if (this.vb) {
  45035. this._engine._releaseBuffer(this.vb);
  45036. this.vb = null;
  45037. }
  45038. if (this.ib) {
  45039. this._engine._releaseBuffer(this.ib);
  45040. this.ib = null;
  45041. }
  45042. if (this.texture) {
  45043. this.texture.dispose();
  45044. this.texture = null;
  45045. }
  45046. this.effect = null;
  45047. this.effectInstanced = null;
  45048. return true;
  45049. };
  45050. return Sprite2DRenderCache;
  45051. }(BABYLON.ModelRenderCache));
  45052. BABYLON.Sprite2DRenderCache = Sprite2DRenderCache;
  45053. var Sprite2DInstanceData = (function (_super) {
  45054. __extends(Sprite2DInstanceData, _super);
  45055. function Sprite2DInstanceData(partId) {
  45056. _super.call(this, partId, 1);
  45057. }
  45058. Object.defineProperty(Sprite2DInstanceData.prototype, "topLeftUV", {
  45059. get: function () {
  45060. return null;
  45061. },
  45062. enumerable: true,
  45063. configurable: true
  45064. });
  45065. Object.defineProperty(Sprite2DInstanceData.prototype, "sizeUV", {
  45066. get: function () {
  45067. return null;
  45068. },
  45069. enumerable: true,
  45070. configurable: true
  45071. });
  45072. Object.defineProperty(Sprite2DInstanceData.prototype, "scaleFactor", {
  45073. get: function () {
  45074. return null;
  45075. },
  45076. enumerable: true,
  45077. configurable: true
  45078. });
  45079. Object.defineProperty(Sprite2DInstanceData.prototype, "textureSize", {
  45080. get: function () {
  45081. return null;
  45082. },
  45083. enumerable: true,
  45084. configurable: true
  45085. });
  45086. Object.defineProperty(Sprite2DInstanceData.prototype, "properties", {
  45087. // 3 floats being:
  45088. // - x: frame number to display
  45089. // - y: invertY setting
  45090. // - z: alignToPixel setting
  45091. get: function () {
  45092. return null;
  45093. },
  45094. enumerable: true,
  45095. configurable: true
  45096. });
  45097. __decorate([
  45098. BABYLON.instanceData()
  45099. ], Sprite2DInstanceData.prototype, "topLeftUV", null);
  45100. __decorate([
  45101. BABYLON.instanceData()
  45102. ], Sprite2DInstanceData.prototype, "sizeUV", null);
  45103. __decorate([
  45104. BABYLON.instanceData()
  45105. ], Sprite2DInstanceData.prototype, "scaleFactor", null);
  45106. __decorate([
  45107. BABYLON.instanceData()
  45108. ], Sprite2DInstanceData.prototype, "textureSize", null);
  45109. __decorate([
  45110. BABYLON.instanceData()
  45111. ], Sprite2DInstanceData.prototype, "properties", null);
  45112. return Sprite2DInstanceData;
  45113. }(BABYLON.InstanceDataBase));
  45114. BABYLON.Sprite2DInstanceData = Sprite2DInstanceData;
  45115. var Sprite2D = (function (_super) {
  45116. __extends(Sprite2D, _super);
  45117. /**
  45118. * Create an 2D Sprite primitive
  45119. * @param texture the texture that stores the sprite to render
  45120. * @param settings a combination of settings, possible ones are
  45121. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  45122. * - children: an array of direct children
  45123. * - id a text identifier, for information purpose
  45124. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45125. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45126. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45127. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45128. * - zOrder: override the zOrder with the specified value
  45129. * - origin: define the normalized origin point location, default [0.5;0.5]
  45130. * - spriteSize: the size of the sprite (in pixels), if null the size of the given texture will be used, default is null.
  45131. * - spriteLocation: the location (in pixels) in the texture of the top/left corner of the Sprite to display, default is null (0,0)
  45132. * - spriteScaleFactor: say you want to display a sprite twice as big as its bitmap which is 64,64, you set the spriteSize to 128,128 and have to set the spriteScaleFactory to 0.5,0.5 in order to address only the 64,64 pixels of the bitmaps. Default is 1,1.
  45133. * - invertY: if true the texture Y will be inverted, default is false.
  45134. * - alignToPixel: if true the sprite's texels will be aligned to the rendering viewport pixels, ensuring the best rendering quality but slow animations won't be done as smooth as if you set false. If false a texel could lies between two pixels, being blended by the texture sampling mode you choose, the rendering result won't be as good, but very slow animation will be overall better looking. Default is true: content will be aligned.
  45135. * - isVisible: true if the sprite must be visible, false for hidden. Default is true.
  45136. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  45137. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  45138. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  45139. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45140. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45141. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45142. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45143. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45144. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45145. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45146. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45147. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45148. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45149. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45150. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45151. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45152. */
  45153. function Sprite2D(texture, settings) {
  45154. var _this = this;
  45155. if (!settings) {
  45156. settings = {};
  45157. }
  45158. _super.call(this, settings);
  45159. this.texture = texture;
  45160. this.texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45161. this.texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45162. this.size = settings.spriteSize;
  45163. this.spriteLocation = settings.spriteLocation || new BABYLON.Vector2(0, 0);
  45164. this.spriteScaleFactor = settings.spriteScaleFactor || new BABYLON.Vector2(1, 1);
  45165. this.spriteFrame = 0;
  45166. this.invertY = (settings.invertY == null) ? false : settings.invertY;
  45167. this.alignToPixel = (settings.alignToPixel == null) ? true : settings.alignToPixel;
  45168. this.useAlphaFromTexture = true;
  45169. if (settings.spriteSize == null || !texture.isReady()) {
  45170. if (texture.isReady()) {
  45171. this.size = texture.getBaseSize();
  45172. }
  45173. else {
  45174. texture.onLoadObservable.add(function () {
  45175. if (settings.spriteSize == null) {
  45176. _this.size = texture.getBaseSize();
  45177. }
  45178. _this._positioningDirty();
  45179. _this._instanceDirtyFlags |= BABYLON.Prim2DBase.originProperty.flagId | Sprite2D.textureProperty.flagId; // To make sure the sprite is issued again for render
  45180. });
  45181. }
  45182. }
  45183. }
  45184. Object.defineProperty(Sprite2D.prototype, "texture", {
  45185. get: function () {
  45186. return this._texture;
  45187. },
  45188. set: function (value) {
  45189. this._texture = value;
  45190. this._oldTextureHasAlpha = this._texture && this.texture.hasAlpha;
  45191. },
  45192. enumerable: true,
  45193. configurable: true
  45194. });
  45195. Object.defineProperty(Sprite2D.prototype, "useAlphaFromTexture", {
  45196. get: function () {
  45197. return this._useAlphaFromTexture;
  45198. },
  45199. set: function (value) {
  45200. if (this._useAlphaFromTexture === value) {
  45201. return;
  45202. }
  45203. this._useAlphaFromTexture = value;
  45204. this._updateRenderMode();
  45205. },
  45206. enumerable: true,
  45207. configurable: true
  45208. });
  45209. Object.defineProperty(Sprite2D.prototype, "actualSize", {
  45210. get: function () {
  45211. if (this._actualSize) {
  45212. return this._actualSize;
  45213. }
  45214. return this.size;
  45215. },
  45216. set: function (value) {
  45217. this._actualSize = value;
  45218. },
  45219. enumerable: true,
  45220. configurable: true
  45221. });
  45222. Object.defineProperty(Sprite2D.prototype, "spriteLocation", {
  45223. get: function () {
  45224. return this._location;
  45225. },
  45226. set: function (value) {
  45227. this._location = value;
  45228. },
  45229. enumerable: true,
  45230. configurable: true
  45231. });
  45232. Object.defineProperty(Sprite2D.prototype, "spriteFrame", {
  45233. get: function () {
  45234. return this._spriteFrame;
  45235. },
  45236. set: function (value) {
  45237. this._spriteFrame = value;
  45238. },
  45239. enumerable: true,
  45240. configurable: true
  45241. });
  45242. Object.defineProperty(Sprite2D.prototype, "invertY", {
  45243. get: function () {
  45244. return this._invertY;
  45245. },
  45246. set: function (value) {
  45247. this._invertY = value;
  45248. },
  45249. enumerable: true,
  45250. configurable: true
  45251. });
  45252. Object.defineProperty(Sprite2D.prototype, "spriteScaleFactor", {
  45253. get: function () {
  45254. return this._spriteScaleFactor;
  45255. },
  45256. set: function (value) {
  45257. this._spriteScaleFactor = value;
  45258. },
  45259. enumerable: true,
  45260. configurable: true
  45261. });
  45262. Object.defineProperty(Sprite2D.prototype, "alignToPixel", {
  45263. /**
  45264. * Get/set if the sprite rendering should be aligned to the target rendering device pixel or not
  45265. */
  45266. get: function () {
  45267. return this._alignToPixel;
  45268. },
  45269. set: function (value) {
  45270. this._alignToPixel = value;
  45271. },
  45272. enumerable: true,
  45273. configurable: true
  45274. });
  45275. Sprite2D.prototype.updateLevelBoundingInfo = function () {
  45276. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.size, this._levelBoundingInfo);
  45277. };
  45278. /**
  45279. * Get the animatable array (see http://doc.babylonjs.com/tutorials/Animations)
  45280. */
  45281. Sprite2D.prototype.getAnimatables = function () {
  45282. var res = new Array();
  45283. if (this.texture && this.texture.animations && this.texture.animations.length > 0) {
  45284. res.push(this.texture);
  45285. }
  45286. return res;
  45287. };
  45288. Sprite2D.prototype.levelIntersect = function (intersectInfo) {
  45289. // If we've made it so far it means the boundingInfo intersection test succeed, the Sprite2D is shaped the same, so we always return true
  45290. return true;
  45291. };
  45292. Sprite2D._createCachedCanvasSprite = function (owner, texture, size, pos) {
  45293. var sprite = new Sprite2D(texture, { parent: owner, id: "__cachedCanvasSprite__", position: BABYLON.Vector2.Zero(), origin: BABYLON.Vector2.Zero(), spriteSize: size, spriteLocation: pos, alignToPixel: true });
  45294. return sprite;
  45295. };
  45296. Sprite2D.prototype.createModelRenderCache = function (modelKey) {
  45297. var renderCache = new Sprite2DRenderCache(this.owner.engine, modelKey);
  45298. return renderCache;
  45299. };
  45300. Sprite2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45301. var renderCache = modelRenderCache;
  45302. var engine = this.owner.engine;
  45303. var vb = new Float32Array(4);
  45304. for (var i = 0; i < 4; i++) {
  45305. vb[i] = i;
  45306. }
  45307. renderCache.vb = engine.createVertexBuffer(vb);
  45308. var ib = new Float32Array(6);
  45309. ib[0] = 0;
  45310. ib[1] = 2;
  45311. ib[2] = 1;
  45312. ib[3] = 0;
  45313. ib[4] = 3;
  45314. ib[5] = 2;
  45315. renderCache.ib = engine.createIndexBuffer(ib);
  45316. renderCache.texture = this.texture;
  45317. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  45318. var ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], true);
  45319. if (ei) {
  45320. renderCache.effectInstanced = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45321. }
  45322. ei = this.getDataPartEffectInfo(Sprite2D.SPRITE2D_MAINPARTID, ["index"], ["alphaTest"], false);
  45323. renderCache.effect = engine.createEffect("sprite2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45324. return renderCache;
  45325. };
  45326. Sprite2D.prototype.createInstanceDataParts = function () {
  45327. return [new Sprite2DInstanceData(Sprite2D.SPRITE2D_MAINPARTID)];
  45328. };
  45329. Sprite2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  45330. Sprite2D.layoutConstructMode = true;
  45331. };
  45332. // if obj contains something, we restore the _text property
  45333. Sprite2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  45334. Sprite2D.layoutConstructMode = false;
  45335. };
  45336. Sprite2D.prototype.refreshInstanceDataPart = function (part) {
  45337. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45338. return false;
  45339. }
  45340. if (!this.texture.isReady() && !Sprite2D.layoutConstructMode) {
  45341. return false;
  45342. }
  45343. if (part.id === Sprite2D.SPRITE2D_MAINPARTID) {
  45344. var d = this._instanceDataParts[0];
  45345. if (Sprite2D.layoutConstructMode) {
  45346. d.topLeftUV = BABYLON.Vector2.Zero();
  45347. d.sizeUV = BABYLON.Vector2.Zero();
  45348. d.properties = BABYLON.Vector3.Zero();
  45349. d.textureSize = BABYLON.Vector2.Zero();
  45350. d.scaleFactor = BABYLON.Vector2.Zero();
  45351. }
  45352. else {
  45353. var ts = this.texture.getBaseSize();
  45354. var sl = this.spriteLocation;
  45355. var ss = this.actualSize;
  45356. var ssf = this.spriteScaleFactor;
  45357. d.topLeftUV = new BABYLON.Vector2(sl.x / ts.width, sl.y / ts.height);
  45358. var suv = new BABYLON.Vector2(ss.width / ts.width, ss.height / ts.height);
  45359. d.sizeUV = suv;
  45360. d.scaleFactor = ssf;
  45361. Sprite2D._prop.x = this.spriteFrame;
  45362. Sprite2D._prop.y = this.invertY ? 1 : 0;
  45363. Sprite2D._prop.z = this.alignToPixel ? 1 : 0;
  45364. d.properties = Sprite2D._prop;
  45365. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  45366. }
  45367. }
  45368. return true;
  45369. };
  45370. Sprite2D.prototype._mustUpdateInstance = function () {
  45371. var res = this._oldTextureHasAlpha !== (this.texture != null && this.texture.hasAlpha);
  45372. this._oldTextureHasAlpha = this.texture != null && this.texture.hasAlpha;
  45373. if (res) {
  45374. this._updateRenderMode();
  45375. }
  45376. return res;
  45377. };
  45378. Sprite2D.prototype._useTextureAlpha = function () {
  45379. return this.texture != null && this.texture.hasAlpha;
  45380. };
  45381. Sprite2D.prototype._shouldUseAlphaFromTexture = function () {
  45382. return this.texture != null && this.texture.hasAlpha && this.useAlphaFromTexture;
  45383. };
  45384. Sprite2D.SPRITE2D_MAINPARTID = 1;
  45385. Sprite2D._prop = BABYLON.Vector3.Zero();
  45386. Sprite2D.layoutConstructMode = false;
  45387. __decorate([
  45388. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Sprite2D.textureProperty = pi; })
  45389. ], Sprite2D.prototype, "texture", null);
  45390. __decorate([
  45391. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Sprite2D.useAlphaFromTextureProperty = pi; })
  45392. ], Sprite2D.prototype, "useAlphaFromTexture", null);
  45393. __decorate([
  45394. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Sprite2D.actualSizeProperty = pi; }, false, true)
  45395. ], Sprite2D.prototype, "actualSize", null);
  45396. __decorate([
  45397. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Sprite2D.spriteLocationProperty = pi; })
  45398. ], Sprite2D.prototype, "spriteLocation", null);
  45399. __decorate([
  45400. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 5, function (pi) { return Sprite2D.spriteFrameProperty = pi; })
  45401. ], Sprite2D.prototype, "spriteFrame", null);
  45402. __decorate([
  45403. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 6, function (pi) { return Sprite2D.invertYProperty = pi; })
  45404. ], Sprite2D.prototype, "invertY", null);
  45405. __decorate([
  45406. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 7, function (pi) { return Sprite2D.spriteScaleFactorProperty = pi; })
  45407. ], Sprite2D.prototype, "spriteScaleFactor", null);
  45408. Sprite2D = __decorate([
  45409. BABYLON.className("Sprite2D")
  45410. ], Sprite2D);
  45411. return Sprite2D;
  45412. }(BABYLON.RenderablePrim2D));
  45413. BABYLON.Sprite2D = Sprite2D;
  45414. })(BABYLON || (BABYLON = {}));
  45415. var BABYLON;
  45416. (function (BABYLON) {
  45417. var Text2DRenderCache = (function (_super) {
  45418. __extends(Text2DRenderCache, _super);
  45419. function Text2DRenderCache() {
  45420. _super.apply(this, arguments);
  45421. this.effectsReady = false;
  45422. this.vb = null;
  45423. this.ib = null;
  45424. this.instancingAttributes = null;
  45425. this.fontTexture = null;
  45426. this.effect = null;
  45427. this.effectInstanced = null;
  45428. }
  45429. Text2DRenderCache.prototype.render = function (instanceInfo, context) {
  45430. // Do nothing if the shader is still loading/preparing
  45431. if (!this.effectsReady) {
  45432. if ((this.effect && (!this.effect.isReady() || (this.effectInstanced && !this.effectInstanced.isReady())))) {
  45433. return false;
  45434. }
  45435. this.effectsReady = true;
  45436. }
  45437. var canvas = instanceInfo.owner.owner;
  45438. var engine = canvas.engine;
  45439. this.fontTexture.update();
  45440. var effect = context.useInstancing ? this.effectInstanced : this.effect;
  45441. engine.enableEffect(effect);
  45442. effect.setTexture("diffuseSampler", this.fontTexture);
  45443. engine.bindBuffersDirectly(this.vb, this.ib, [1], 4, effect);
  45444. var curAlphaMode = engine.getAlphaMode();
  45445. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45446. var pid = context.groupInfoPartData[0];
  45447. if (context.useInstancing) {
  45448. if (!this.instancingAttributes) {
  45449. this.instancingAttributes = this.loadInstancingAttributes(Text2D.TEXT2D_MAINPARTID, effect);
  45450. }
  45451. var glBuffer = context.instancedBuffers ? context.instancedBuffers[0] : pid._partBuffer;
  45452. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45453. canvas._addDrawCallCount(1, context.renderMode);
  45454. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingAttributes);
  45455. engine.draw(true, 0, 6, count);
  45456. engine.unbindInstanceAttributes();
  45457. }
  45458. else {
  45459. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45460. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45461. this.setupUniforms(effect, 0, pid._partData, i);
  45462. engine.draw(true, 0, 6);
  45463. }
  45464. }
  45465. engine.setAlphaMode(curAlphaMode, true);
  45466. return true;
  45467. };
  45468. Text2DRenderCache.prototype.dispose = function () {
  45469. if (!_super.prototype.dispose.call(this)) {
  45470. return false;
  45471. }
  45472. if (this.vb) {
  45473. this._engine._releaseBuffer(this.vb);
  45474. this.vb = null;
  45475. }
  45476. if (this.ib) {
  45477. this._engine._releaseBuffer(this.ib);
  45478. this.ib = null;
  45479. }
  45480. if (this.fontTexture) {
  45481. this.fontTexture.decCachedFontTextureCounter();
  45482. this.fontTexture = null;
  45483. }
  45484. this.effect = null;
  45485. this.effectInstanced = null;
  45486. return true;
  45487. };
  45488. return Text2DRenderCache;
  45489. }(BABYLON.ModelRenderCache));
  45490. BABYLON.Text2DRenderCache = Text2DRenderCache;
  45491. var Text2DInstanceData = (function (_super) {
  45492. __extends(Text2DInstanceData, _super);
  45493. function Text2DInstanceData(partId, dataElementCount) {
  45494. _super.call(this, partId, dataElementCount);
  45495. }
  45496. Object.defineProperty(Text2DInstanceData.prototype, "topLeftUV", {
  45497. get: function () {
  45498. return null;
  45499. },
  45500. enumerable: true,
  45501. configurable: true
  45502. });
  45503. Object.defineProperty(Text2DInstanceData.prototype, "sizeUV", {
  45504. get: function () {
  45505. return null;
  45506. },
  45507. enumerable: true,
  45508. configurable: true
  45509. });
  45510. Object.defineProperty(Text2DInstanceData.prototype, "textureSize", {
  45511. get: function () {
  45512. return null;
  45513. },
  45514. enumerable: true,
  45515. configurable: true
  45516. });
  45517. Object.defineProperty(Text2DInstanceData.prototype, "color", {
  45518. get: function () {
  45519. return null;
  45520. },
  45521. enumerable: true,
  45522. configurable: true
  45523. });
  45524. Object.defineProperty(Text2DInstanceData.prototype, "superSampleFactor", {
  45525. get: function () {
  45526. return null;
  45527. },
  45528. enumerable: true,
  45529. configurable: true
  45530. });
  45531. __decorate([
  45532. BABYLON.instanceData()
  45533. ], Text2DInstanceData.prototype, "topLeftUV", null);
  45534. __decorate([
  45535. BABYLON.instanceData()
  45536. ], Text2DInstanceData.prototype, "sizeUV", null);
  45537. __decorate([
  45538. BABYLON.instanceData()
  45539. ], Text2DInstanceData.prototype, "textureSize", null);
  45540. __decorate([
  45541. BABYLON.instanceData()
  45542. ], Text2DInstanceData.prototype, "color", null);
  45543. __decorate([
  45544. BABYLON.instanceData()
  45545. ], Text2DInstanceData.prototype, "superSampleFactor", null);
  45546. return Text2DInstanceData;
  45547. }(BABYLON.InstanceDataBase));
  45548. BABYLON.Text2DInstanceData = Text2DInstanceData;
  45549. var Text2D = (function (_super) {
  45550. __extends(Text2D, _super);
  45551. /**
  45552. * Create a Text primitive
  45553. * @param text the text to display
  45554. * @param settings a combination of settings, possible ones are
  45555. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  45556. * - children: an array of direct children
  45557. * - id a text identifier, for information purpose
  45558. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  45559. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  45560. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  45561. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  45562. * - zOrder: override the zOrder with the specified value
  45563. * - origin: define the normalized origin point location, default [0.5;0.5]
  45564. * - fontName: the name/size/style of the font to use, following the CSS notation. Default is "12pt Arial".
  45565. * - fontSuperSample: if true the text will be rendered with a superSampled font (the font is twice the given size). Use this settings if the text lies in world space or if it's scaled in.
  45566. * - defaultFontColor: the color by default to apply on each letter of the text to display, default is plain white.
  45567. * - areaSize: the size of the area in which to display the text, default is auto-fit from text content.
  45568. * - tabulationSize: number of space character to insert when a tabulation is encountered, default is 4
  45569. * - isVisible: true if the text must be visible, false for hidden. Default is true.
  45570. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  45571. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  45572. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  45573. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45574. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45575. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45576. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45577. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  45578. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  45579. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  45580. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  45581. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45582. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45583. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45584. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  45585. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  45586. */
  45587. function Text2D(text, settings) {
  45588. if (!settings) {
  45589. settings = {};
  45590. }
  45591. _super.call(this, settings);
  45592. this.fontName = (settings.fontName == null) ? "12pt Arial" : settings.fontName;
  45593. this._fontSuperSample = (settings.fontSuperSample != null && settings.fontSuperSample);
  45594. this.defaultFontColor = (settings.defaultFontColor == null) ? new BABYLON.Color4(1, 1, 1, 1) : settings.defaultFontColor;
  45595. this._tabulationSize = (settings.tabulationSize == null) ? 4 : settings.tabulationSize;
  45596. this._textSize = null;
  45597. this.text = text;
  45598. this.size = (settings.size == null) ? null : settings.size;
  45599. this._updateRenderMode();
  45600. }
  45601. Object.defineProperty(Text2D.prototype, "fontName", {
  45602. get: function () {
  45603. return this._fontName;
  45604. },
  45605. set: function (value) {
  45606. if (this._fontName) {
  45607. throw new Error("Font Name change is not supported right now.");
  45608. }
  45609. this._fontName = value;
  45610. },
  45611. enumerable: true,
  45612. configurable: true
  45613. });
  45614. Object.defineProperty(Text2D.prototype, "defaultFontColor", {
  45615. get: function () {
  45616. return this._defaultFontColor;
  45617. },
  45618. set: function (value) {
  45619. this._defaultFontColor = value;
  45620. },
  45621. enumerable: true,
  45622. configurable: true
  45623. });
  45624. Object.defineProperty(Text2D.prototype, "text", {
  45625. get: function () {
  45626. return this._text;
  45627. },
  45628. set: function (value) {
  45629. this._text = value;
  45630. this._textSize = null; // A change of text will reset the TextSize which will be recomputed next time it's used
  45631. this._size = null;
  45632. this._updateCharCount();
  45633. // Trigger a textSize to for a sizeChange if necessary, which is needed for layout to recompute
  45634. var s = this.textSize;
  45635. },
  45636. enumerable: true,
  45637. configurable: true
  45638. });
  45639. Object.defineProperty(Text2D.prototype, "size", {
  45640. get: function () {
  45641. if (this._size != null) {
  45642. return this._size;
  45643. }
  45644. return this.textSize;
  45645. },
  45646. set: function (value) {
  45647. this._size = value;
  45648. },
  45649. enumerable: true,
  45650. configurable: true
  45651. });
  45652. Object.defineProperty(Text2D.prototype, "actualSize", {
  45653. /**
  45654. * Get the actual size of the Text2D primitive
  45655. */
  45656. get: function () {
  45657. if (this._actualSize) {
  45658. return this._actualSize;
  45659. }
  45660. return this.size;
  45661. },
  45662. enumerable: true,
  45663. configurable: true
  45664. });
  45665. Object.defineProperty(Text2D.prototype, "textSize", {
  45666. /**
  45667. * Get the area that bounds the text associated to the primitive
  45668. */
  45669. get: function () {
  45670. if (!this._textSize) {
  45671. if (this.owner) {
  45672. var newSize = this.fontTexture.measureText(this._text, this._tabulationSize);
  45673. if (!newSize.equals(this._textSize)) {
  45674. this.onPrimitivePropertyDirty(BABYLON.Prim2DBase.sizeProperty.flagId);
  45675. this._positioningDirty();
  45676. }
  45677. this._textSize = newSize;
  45678. }
  45679. else {
  45680. return Text2D.nullSize;
  45681. }
  45682. }
  45683. return this._textSize;
  45684. },
  45685. enumerable: true,
  45686. configurable: true
  45687. });
  45688. Object.defineProperty(Text2D.prototype, "fontTexture", {
  45689. get: function () {
  45690. if (this._fontTexture) {
  45691. return this._fontTexture;
  45692. }
  45693. if (this.fontName == null || this.owner == null || this.owner.scene == null) {
  45694. return null;
  45695. }
  45696. this._fontTexture = BABYLON.FontTexture.GetCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  45697. return this._fontTexture;
  45698. },
  45699. enumerable: true,
  45700. configurable: true
  45701. });
  45702. /**
  45703. * Dispose the primitive, remove it from its parent
  45704. */
  45705. Text2D.prototype.dispose = function () {
  45706. if (!_super.prototype.dispose.call(this)) {
  45707. return false;
  45708. }
  45709. if (this._fontTexture) {
  45710. BABYLON.FontTexture.ReleaseCachedFontTexture(this.owner.scene, this.fontName, this._fontSuperSample);
  45711. this._fontTexture = null;
  45712. }
  45713. return true;
  45714. };
  45715. Text2D.prototype.updateLevelBoundingInfo = function () {
  45716. BABYLON.BoundingInfo2D.CreateFromSizeToRef(this.actualSize, this._levelBoundingInfo);
  45717. };
  45718. Text2D.prototype.levelIntersect = function (intersectInfo) {
  45719. // For now I can't do something better that boundingInfo is a hit, detecting an intersection on a particular letter would be possible, but do we really need it? Not for now...
  45720. return true;
  45721. };
  45722. Text2D.prototype.createModelRenderCache = function (modelKey) {
  45723. var renderCache = new Text2DRenderCache(this.owner.engine, modelKey);
  45724. return renderCache;
  45725. };
  45726. Text2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  45727. var renderCache = modelRenderCache;
  45728. var engine = this.owner.engine;
  45729. renderCache.fontTexture = this.fontTexture;
  45730. renderCache.fontTexture.incCachedFontTextureCounter();
  45731. var vb = new Float32Array(4);
  45732. for (var i = 0; i < 4; i++) {
  45733. vb[i] = i;
  45734. }
  45735. renderCache.vb = engine.createVertexBuffer(vb);
  45736. var ib = new Float32Array(6);
  45737. ib[0] = 0;
  45738. ib[1] = 2;
  45739. ib[2] = 1;
  45740. ib[3] = 0;
  45741. ib[4] = 3;
  45742. ib[5] = 2;
  45743. renderCache.ib = engine.createIndexBuffer(ib);
  45744. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  45745. var ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, true);
  45746. if (ei) {
  45747. renderCache.effectInstanced = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45748. }
  45749. ei = this.getDataPartEffectInfo(Text2D.TEXT2D_MAINPARTID, ["index"], null, false);
  45750. renderCache.effect = engine.createEffect("text2d", ei.attributes, ei.uniforms, ["diffuseSampler"], ei.defines, null);
  45751. return renderCache;
  45752. };
  45753. Text2D.prototype.createInstanceDataParts = function () {
  45754. return [new Text2DInstanceData(Text2D.TEXT2D_MAINPARTID, this._charCount)];
  45755. };
  45756. // Looks like a hack!? Yes! Because that's what it is!
  45757. // For the InstanceData layer to compute correctly we need to set all the properties involved, which won't be the case if there's no text
  45758. // This method is called before the layout construction for us to detect this case, set some text and return the initial one to restore it after (there can be some text without char to display, say "\t\n" for instance)
  45759. Text2D.prototype.beforeRefreshForLayoutConstruction = function (part) {
  45760. if (!this._charCount) {
  45761. var curText = this._text;
  45762. this.text = "A";
  45763. return curText;
  45764. }
  45765. };
  45766. // if obj contains something, we restore the _text property
  45767. Text2D.prototype.afterRefreshForLayoutConstruction = function (part, obj) {
  45768. if (obj !== undefined) {
  45769. this.text = obj;
  45770. }
  45771. };
  45772. Text2D.prototype.refreshInstanceDataPart = function (part) {
  45773. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  45774. return false;
  45775. }
  45776. if (part.id === Text2D.TEXT2D_MAINPARTID) {
  45777. var d = part;
  45778. var texture = this.fontTexture;
  45779. var superSampleFactor = texture.isSuperSampled ? 0.5 : 1;
  45780. var ts = texture.getSize();
  45781. var offset = BABYLON.Vector2.Zero();
  45782. var lh = this.fontTexture.lineHeight;
  45783. offset.y = ((this.textSize.height / lh) - 1) * lh; // Origin is bottom, not top, so the offset is starting with a y that is the top location of the text
  45784. var charxpos = 0;
  45785. d.dataElementCount = this._charCount;
  45786. d.curElement = 0;
  45787. for (var _i = 0, _a = this.text; _i < _a.length; _i++) {
  45788. var char = _a[_i];
  45789. // Line feed
  45790. if (char === "\n") {
  45791. offset.x = 0;
  45792. offset.y -= texture.lineHeight;
  45793. }
  45794. // Tabulation ?
  45795. if (char === "\t") {
  45796. var nextPos = charxpos + this._tabulationSize;
  45797. nextPos = nextPos - (nextPos % this._tabulationSize);
  45798. offset.x += (nextPos - charxpos) * texture.spaceWidth;
  45799. charxpos = nextPos;
  45800. continue;
  45801. }
  45802. if (char < " ") {
  45803. continue;
  45804. }
  45805. this.updateInstanceDataPart(d, offset);
  45806. var ci = texture.getChar(char);
  45807. offset.x += ci.charWidth;
  45808. d.topLeftUV = ci.topLeftUV;
  45809. var suv = ci.bottomRightUV.subtract(ci.topLeftUV);
  45810. d.sizeUV = suv;
  45811. d.textureSize = new BABYLON.Vector2(ts.width, ts.height);
  45812. d.color = this.defaultFontColor;
  45813. d.superSampleFactor = superSampleFactor;
  45814. ++d.curElement;
  45815. }
  45816. }
  45817. return true;
  45818. };
  45819. Text2D.prototype._updateCharCount = function () {
  45820. var count = 0;
  45821. for (var _i = 0, _a = this._text; _i < _a.length; _i++) {
  45822. var char = _a[_i];
  45823. if (char === "\r" || char === "\n" || char === "\t" || char < " ") {
  45824. continue;
  45825. }
  45826. ++count;
  45827. }
  45828. this._charCount = count;
  45829. };
  45830. Text2D.prototype._useTextureAlpha = function () {
  45831. return this.fontTexture != null && this.fontTexture.hasAlpha;
  45832. };
  45833. Text2D.prototype._shouldUseAlphaFromTexture = function () {
  45834. return true;
  45835. };
  45836. Text2D.TEXT2D_MAINPARTID = 1;
  45837. __decorate([
  45838. BABYLON.modelLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 1, function (pi) { return Text2D.fontProperty = pi; }, false, true)
  45839. ], Text2D.prototype, "fontName", null);
  45840. __decorate([
  45841. BABYLON.dynamicLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 2, function (pi) { return Text2D.defaultFontColorProperty = pi; })
  45842. ], Text2D.prototype, "defaultFontColor", null);
  45843. __decorate([
  45844. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 3, function (pi) { return Text2D.textProperty = pi; }, false, true)
  45845. ], Text2D.prototype, "text", null);
  45846. __decorate([
  45847. BABYLON.instanceLevelProperty(BABYLON.RenderablePrim2D.RENDERABLEPRIM2D_PROPCOUNT + 4, function (pi) { return Text2D.sizeProperty = pi; })
  45848. ], Text2D.prototype, "size", null);
  45849. Text2D = __decorate([
  45850. BABYLON.className("Text2D")
  45851. ], Text2D);
  45852. return Text2D;
  45853. }(BABYLON.RenderablePrim2D));
  45854. BABYLON.Text2D = Text2D;
  45855. })(BABYLON || (BABYLON = {}));
  45856. var BABYLON;
  45857. (function (BABYLON) {
  45858. var Lines2DRenderCache = (function (_super) {
  45859. __extends(Lines2DRenderCache, _super);
  45860. function Lines2DRenderCache(engine, modelKey) {
  45861. _super.call(this, engine, modelKey);
  45862. this.effectsReady = false;
  45863. this.fillVB = null;
  45864. this.fillIB = null;
  45865. this.fillIndicesCount = 0;
  45866. this.instancingFillAttributes = null;
  45867. this.effectFill = null;
  45868. this.effectFillInstanced = null;
  45869. this.borderVB = null;
  45870. this.borderIB = null;
  45871. this.borderIndicesCount = 0;
  45872. this.instancingBorderAttributes = null;
  45873. this.effectBorder = null;
  45874. this.effectBorderInstanced = null;
  45875. }
  45876. Lines2DRenderCache.prototype.render = function (instanceInfo, context) {
  45877. // Do nothing if the shader is still loading/preparing
  45878. if (!this.effectsReady) {
  45879. if ((this.effectFill && (!this.effectFill.isReady() || (this.effectFillInstanced && !this.effectFillInstanced.isReady()))) ||
  45880. (this.effectBorder && (!this.effectBorder.isReady() || (this.effectBorderInstanced && !this.effectBorderInstanced.isReady())))) {
  45881. return false;
  45882. }
  45883. this.effectsReady = true;
  45884. }
  45885. var canvas = instanceInfo.owner.owner;
  45886. var engine = canvas.engine;
  45887. var depthFunction = 0;
  45888. if (this.effectFill && this.effectBorder) {
  45889. depthFunction = engine.getDepthFunction();
  45890. engine.setDepthFunctionToLessOrEqual();
  45891. }
  45892. var curAlphaMode = engine.getAlphaMode();
  45893. if (this.effectFill) {
  45894. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_FILLPARTID.toString());
  45895. var pid = context.groupInfoPartData[partIndex];
  45896. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45897. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45898. }
  45899. var effect = context.useInstancing ? this.effectFillInstanced : this.effectFill;
  45900. engine.enableEffect(effect);
  45901. engine.bindBuffersDirectly(this.fillVB, this.fillIB, [2], 2 * 4, effect);
  45902. if (context.useInstancing) {
  45903. if (!this.instancingFillAttributes) {
  45904. this.instancingFillAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_FILLPARTID, effect);
  45905. }
  45906. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45907. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45908. canvas._addDrawCallCount(1, context.renderMode);
  45909. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingFillAttributes);
  45910. engine.draw(true, 0, this.fillIndicesCount, count);
  45911. engine.unbindInstanceAttributes();
  45912. }
  45913. else {
  45914. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45915. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45916. this.setupUniforms(effect, partIndex, pid._partData, i);
  45917. engine.draw(true, 0, this.fillIndicesCount);
  45918. }
  45919. }
  45920. }
  45921. if (this.effectBorder) {
  45922. var partIndex = instanceInfo.partIndexFromId.get(BABYLON.Shape2D.SHAPE2D_BORDERPARTID.toString());
  45923. var pid = context.groupInfoPartData[partIndex];
  45924. if (context.renderMode !== BABYLON.Render2DContext.RenderModeOpaque) {
  45925. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE, true);
  45926. }
  45927. var effect = context.useInstancing ? this.effectBorderInstanced : this.effectBorder;
  45928. engine.enableEffect(effect);
  45929. engine.bindBuffersDirectly(this.borderVB, this.borderIB, [2], 2 * 4, effect);
  45930. if (context.useInstancing) {
  45931. if (!this.instancingBorderAttributes) {
  45932. this.instancingBorderAttributes = this.loadInstancingAttributes(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, effect);
  45933. }
  45934. var glBuffer = context.instancedBuffers ? context.instancedBuffers[partIndex] : pid._partBuffer;
  45935. var count = context.instancedBuffers ? context.instancesCount : pid._partData.usedElementCount;
  45936. canvas._addDrawCallCount(1, context.renderMode);
  45937. engine.updateAndBindInstancesBuffer(glBuffer, null, this.instancingBorderAttributes);
  45938. engine.draw(true, 0, this.borderIndicesCount, count);
  45939. engine.unbindInstanceAttributes();
  45940. }
  45941. else {
  45942. canvas._addDrawCallCount(context.partDataEndIndex - context.partDataStartIndex, context.renderMode);
  45943. for (var i = context.partDataStartIndex; i < context.partDataEndIndex; i++) {
  45944. this.setupUniforms(effect, partIndex, pid._partData, i);
  45945. engine.draw(true, 0, this.borderIndicesCount);
  45946. }
  45947. }
  45948. }
  45949. engine.setAlphaMode(curAlphaMode, true);
  45950. if (this.effectFill && this.effectBorder) {
  45951. engine.setDepthFunction(depthFunction);
  45952. }
  45953. return true;
  45954. };
  45955. Lines2DRenderCache.prototype.dispose = function () {
  45956. if (!_super.prototype.dispose.call(this)) {
  45957. return false;
  45958. }
  45959. if (this.fillVB) {
  45960. this._engine._releaseBuffer(this.fillVB);
  45961. this.fillVB = null;
  45962. }
  45963. if (this.fillIB) {
  45964. this._engine._releaseBuffer(this.fillIB);
  45965. this.fillIB = null;
  45966. }
  45967. this.effectFill = null;
  45968. this.effectFillInstanced = null;
  45969. this.effectBorder = null;
  45970. this.effectBorderInstanced = null;
  45971. if (this.borderVB) {
  45972. this._engine._releaseBuffer(this.borderVB);
  45973. this.borderVB = null;
  45974. }
  45975. if (this.borderIB) {
  45976. this._engine._releaseBuffer(this.borderIB);
  45977. this.borderIB = null;
  45978. }
  45979. return true;
  45980. };
  45981. return Lines2DRenderCache;
  45982. }(BABYLON.ModelRenderCache));
  45983. BABYLON.Lines2DRenderCache = Lines2DRenderCache;
  45984. var Lines2DInstanceData = (function (_super) {
  45985. __extends(Lines2DInstanceData, _super);
  45986. function Lines2DInstanceData(partId) {
  45987. _super.call(this, partId, 1);
  45988. }
  45989. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMin", {
  45990. get: function () {
  45991. return null;
  45992. },
  45993. enumerable: true,
  45994. configurable: true
  45995. });
  45996. Object.defineProperty(Lines2DInstanceData.prototype, "boundingMax", {
  45997. get: function () {
  45998. return null;
  45999. },
  46000. enumerable: true,
  46001. configurable: true
  46002. });
  46003. __decorate([
  46004. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  46005. ], Lines2DInstanceData.prototype, "boundingMin", null);
  46006. __decorate([
  46007. BABYLON.instanceData(BABYLON.Shape2D.SHAPE2D_CATEGORY_FILLGRADIENT)
  46008. ], Lines2DInstanceData.prototype, "boundingMax", null);
  46009. return Lines2DInstanceData;
  46010. }(BABYLON.Shape2DInstanceData));
  46011. BABYLON.Lines2DInstanceData = Lines2DInstanceData;
  46012. var Lines2D = (function (_super) {
  46013. __extends(Lines2D, _super);
  46014. /**
  46015. * Create an 2D Lines Shape primitive. The defined lines may be opened or closed (see below)
  46016. * @param points an array that describe the points to use to draw the line, must contain at least two entries.
  46017. * @param settings a combination of settings, possible ones are
  46018. * - parent: the parent primitive/canvas, must be specified if the primitive is not constructed as a child of another one (i.e. as part of the children array setting)
  46019. * - children: an array of direct children
  46020. * - id a text identifier, for information purpose
  46021. * - position: the X & Y positions relative to its parent. Alternatively the x and y properties can be set. Default is [0;0]
  46022. * - rotation: the initial rotation (in radian) of the primitive. default is 0
  46023. * - scale: the initial scale of the primitive. default is 1. You can alternatively use scaleX &| scaleY to apply non uniform scale
  46024. * - opacity: set the overall opacity of the primitive, 1 to be opaque (default), less than 1 to be transparent.
  46025. * - zOrder: override the zOrder with the specified value
  46026. * - origin: define the normalized origin point location, default [0.5;0.5]
  46027. * - fillThickness: the thickness of the fill part of the line, can be null to draw nothing (but a border brush must be given), default is 1.
  46028. * - closed: if false the lines are said to be opened, the first point and the latest DON'T connect. if true the lines are said to be closed, the first and last point will be connected by a line. For instance you can define the 4 points of a rectangle, if you set closed to true a 4 edges rectangle will be drawn. If you set false, only three edges will be drawn, the edge formed by the first and last point won't exist. Default is false.
  46029. * - startCap: Draw a cap of the given type at the start of the first line, you can't define a Cap if the Lines2D is closed. Default is Lines2D.NoCap.
  46030. * - endCap: Draw a cap of the given type at the end of the last line, you can't define a Cap if the Lines2D is closed. Default is Lines2D.NoCap.
  46031. * - fill: the brush used to draw the fill content of the lines, you can set null to draw nothing (but you will have to set a border brush), default is a SolidColorBrush of plain white. can be a string value (see Canvas2D.GetBrushFromString)
  46032. * - border: the brush used to draw the border of the lines, you can set null to draw nothing (but you will have to set a fill brush), default is null. can be a string value (see Canvas2D.GetBrushFromString)
  46033. * - borderThickness: the thickness of the drawn border, default is 1.
  46034. * - isVisible: true if the primitive must be visible, false for hidden. Default is true.
  46035. * - isPickable: if true the Primitive can be used with interaction mode and will issue Pointer Event. If false it will be ignored for interaction/intersection test. Default value is true.
  46036. * - isContainer: if true the Primitive acts as a container for interaction, if the primitive is not pickable or doesn't intersection, no further test will be perform on its children. If set to false, children will always be considered for intersection/interaction. Default value is true.
  46037. * - childrenFlatZOrder: if true all the children (direct and indirect) will share the same Z-Order. Use this when there's a lot of children which don't overlap. The drawing order IS NOT GUARANTED!
  46038. * - marginTop: top margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46039. * - marginLeft: left margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46040. * - marginRight: right margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46041. * - marginBottom: bottom margin, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46042. * - margin: top, left, right and bottom margin formatted as a single string (see PrimitiveThickness.fromString)
  46043. * - marginHAlignment: one value of the PrimitiveAlignment type's static properties
  46044. * - marginVAlignment: one value of the PrimitiveAlignment type's static properties
  46045. * - marginAlignment: a string defining the alignment, see PrimitiveAlignment.fromString
  46046. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46047. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46048. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46049. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  46050. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  46051. */
  46052. function Lines2D(points, settings) {
  46053. if (!settings) {
  46054. settings = {};
  46055. }
  46056. _super.call(this, settings);
  46057. this._fillVB = null;
  46058. this._fillIB = null;
  46059. this._borderVB = null;
  46060. this._borderIB = null;
  46061. this._size = BABYLON.Size.Zero();
  46062. this._boundingMin = null;
  46063. this._boundingMax = null;
  46064. var fillThickness = (settings.fillThickness == null) ? 1 : settings.fillThickness;
  46065. var startCap = (settings.startCap == null) ? 0 : settings.startCap;
  46066. var endCap = (settings.endCap == null) ? 0 : settings.endCap;
  46067. var closed = (settings.closed == null) ? false : settings.closed;
  46068. this.points = points;
  46069. this.fillThickness = fillThickness;
  46070. this.startCap = startCap;
  46071. this.endCap = endCap;
  46072. this.closed = closed;
  46073. }
  46074. Object.defineProperty(Lines2D, "NoCap", {
  46075. /**
  46076. * No Cap to apply on the extremity
  46077. */
  46078. get: function () { return Lines2D._noCap; },
  46079. enumerable: true,
  46080. configurable: true
  46081. });
  46082. Object.defineProperty(Lines2D, "RoundCap", {
  46083. /**
  46084. * A round cap, will use the line thickness as diameter
  46085. */
  46086. get: function () { return Lines2D._roundCap; },
  46087. enumerable: true,
  46088. configurable: true
  46089. });
  46090. Object.defineProperty(Lines2D, "TriangleCap", {
  46091. /**
  46092. * Creates a triangle at the extremity.
  46093. */
  46094. get: function () { return Lines2D._triangleCap; },
  46095. enumerable: true,
  46096. configurable: true
  46097. });
  46098. Object.defineProperty(Lines2D, "SquareAnchorCap", {
  46099. /**
  46100. * Creates a Square anchor at the extremity, the square size is twice the thickness of the line
  46101. */
  46102. get: function () { return Lines2D._squareAnchorCap; },
  46103. enumerable: true,
  46104. configurable: true
  46105. });
  46106. Object.defineProperty(Lines2D, "RoundAnchorCap", {
  46107. /**
  46108. * Creates a round anchor at the extremity, the diameter is twice the thickness of the line
  46109. */
  46110. get: function () { return Lines2D._roundAnchorCap; },
  46111. enumerable: true,
  46112. configurable: true
  46113. });
  46114. Object.defineProperty(Lines2D, "DiamondAnchorCap", {
  46115. /**
  46116. * Creates a diamond anchor at the extremity.
  46117. */
  46118. get: function () { return Lines2D._diamondAnchorCap; },
  46119. enumerable: true,
  46120. configurable: true
  46121. });
  46122. Object.defineProperty(Lines2D, "ArrowCap", {
  46123. /**
  46124. * Creates an arrow anchor at the extremity. the arrow base size is twice the thickness of the line
  46125. */
  46126. get: function () { return Lines2D._arrowCap; },
  46127. enumerable: true,
  46128. configurable: true
  46129. });
  46130. Object.defineProperty(Lines2D.prototype, "points", {
  46131. get: function () {
  46132. return this._points;
  46133. },
  46134. set: function (value) {
  46135. this._points = value;
  46136. this._contour = null;
  46137. this._boundingBoxDirty();
  46138. },
  46139. enumerable: true,
  46140. configurable: true
  46141. });
  46142. Object.defineProperty(Lines2D.prototype, "fillThickness", {
  46143. get: function () {
  46144. return this._fillThickness;
  46145. },
  46146. set: function (value) {
  46147. this._fillThickness = value;
  46148. },
  46149. enumerable: true,
  46150. configurable: true
  46151. });
  46152. Object.defineProperty(Lines2D.prototype, "closed", {
  46153. get: function () {
  46154. return this._closed;
  46155. },
  46156. set: function (value) {
  46157. this._closed = value;
  46158. },
  46159. enumerable: true,
  46160. configurable: true
  46161. });
  46162. Object.defineProperty(Lines2D.prototype, "startCap", {
  46163. get: function () {
  46164. return this._startCap;
  46165. },
  46166. set: function (value) {
  46167. this._startCap = value;
  46168. },
  46169. enumerable: true,
  46170. configurable: true
  46171. });
  46172. Object.defineProperty(Lines2D.prototype, "endCap", {
  46173. get: function () {
  46174. return this._endCap;
  46175. },
  46176. set: function (value) {
  46177. this._endCap = value;
  46178. },
  46179. enumerable: true,
  46180. configurable: true
  46181. });
  46182. Lines2D.prototype.levelIntersect = function (intersectInfo) {
  46183. var _this = this;
  46184. if (this._contour == null) {
  46185. this._computeLines2D();
  46186. }
  46187. var pl = this.points.length;
  46188. var l = this.closed ? pl + 1 : pl;
  46189. var p = intersectInfo._localPickPosition;
  46190. this.transformPointWithOriginToRef(this._contour[0], null, Lines2D._prevA);
  46191. this.transformPointWithOriginToRef(this._contour[1], null, Lines2D._prevB);
  46192. for (var i = 1; i < l; i++) {
  46193. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 0], null, Lines2D._curA);
  46194. this.transformPointWithOriginToRef(this._contour[(i % pl) * 2 + 1], null, Lines2D._curB);
  46195. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curA)) {
  46196. return true;
  46197. }
  46198. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._curA, Lines2D._prevB, Lines2D._curB)) {
  46199. return true;
  46200. }
  46201. Lines2D._prevA.x = Lines2D._curA.x;
  46202. Lines2D._prevA.y = Lines2D._curA.y;
  46203. Lines2D._prevB.x = Lines2D._curB.x;
  46204. Lines2D._prevB.y = Lines2D._curB.y;
  46205. }
  46206. var capIntersect = function (tri, points) {
  46207. var l = tri.length;
  46208. for (var i = 0; i < l; i += 3) {
  46209. Lines2D._curA.x = points[tri[i + 0] * 2 + 0];
  46210. Lines2D._curA.y = points[tri[i + 0] * 2 + 1];
  46211. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._curB);
  46212. Lines2D._curA.x = points[tri[i + 1] * 2 + 0];
  46213. Lines2D._curA.y = points[tri[i + 1] * 2 + 1];
  46214. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevA);
  46215. Lines2D._curA.x = points[tri[i + 2] * 2 + 0];
  46216. Lines2D._curA.y = points[tri[i + 2] * 2 + 1];
  46217. _this.transformPointWithOriginToRef(Lines2D._curA, null, Lines2D._prevB);
  46218. if (BABYLON.Vector2.PointInTriangle(p, Lines2D._prevA, Lines2D._prevB, Lines2D._curB)) {
  46219. return true;
  46220. }
  46221. }
  46222. return false;
  46223. };
  46224. if (this._startCapTriIndices) {
  46225. if (this._startCapTriIndices && capIntersect(this._startCapTriIndices, this._startCapContour)) {
  46226. return true;
  46227. }
  46228. if (this._endCapTriIndices && capIntersect(this._endCapTriIndices, this._endCapContour)) {
  46229. return true;
  46230. }
  46231. }
  46232. return false;
  46233. };
  46234. Object.defineProperty(Lines2D.prototype, "boundingMin", {
  46235. get: function () {
  46236. if (!this._boundingMin) {
  46237. this._computeLines2D();
  46238. }
  46239. return this._boundingMin;
  46240. },
  46241. enumerable: true,
  46242. configurable: true
  46243. });
  46244. Object.defineProperty(Lines2D.prototype, "boundingMax", {
  46245. get: function () {
  46246. if (!this._boundingMax) {
  46247. this._computeLines2D();
  46248. }
  46249. return this._boundingMax;
  46250. },
  46251. enumerable: true,
  46252. configurable: true
  46253. });
  46254. Lines2D.prototype.getUsedShaderCategories = function (dataPart) {
  46255. var res = _super.prototype.getUsedShaderCategories.call(this, dataPart);
  46256. // Remove the BORDER category, we don't use it in the VertexShader
  46257. var i = res.indexOf(BABYLON.Shape2D.SHAPE2D_CATEGORY_BORDER);
  46258. if (i !== -1) {
  46259. res.splice(i, 1);
  46260. }
  46261. return res;
  46262. };
  46263. Lines2D.prototype.updateLevelBoundingInfo = function () {
  46264. if (!this._boundingMin) {
  46265. this._computeLines2D();
  46266. }
  46267. BABYLON.BoundingInfo2D.CreateFromMinMaxToRef(this._boundingMin.x, this._boundingMax.x, this._boundingMin.y, this._boundingMax.y, this._levelBoundingInfo);
  46268. };
  46269. Lines2D.prototype.createModelRenderCache = function (modelKey) {
  46270. var renderCache = new Lines2DRenderCache(this.owner.engine, modelKey);
  46271. return renderCache;
  46272. };
  46273. ///////////////////////////////////////////////////////////////////////////////////
  46274. // Methods for Lines building
  46275. Lines2D.prototype._perp = function (v, res) {
  46276. res.x = v.y;
  46277. res.y = -v.x;
  46278. };
  46279. ;
  46280. Lines2D.prototype._direction = function (a, b, res) {
  46281. a.subtractToRef(b, res);
  46282. res.normalize();
  46283. };
  46284. Lines2D.prototype._computeMiter = function (tangent, miter, a, b) {
  46285. a.addToRef(b, tangent);
  46286. tangent.normalize();
  46287. miter.x = -tangent.y;
  46288. miter.y = tangent.x;
  46289. Lines2D._miterTps.x = -a.y;
  46290. Lines2D._miterTps.y = a.x;
  46291. return 1 / BABYLON.Vector2.Dot(miter, Lines2D._miterTps);
  46292. };
  46293. Lines2D.prototype._intersect = function (x1, y1, x2, y2, x3, y3, x4, y4) {
  46294. var d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
  46295. if (d === 0)
  46296. return false;
  46297. var xi = ((x3 - x4) * (x1 * y2 - y1 * x2) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d; // Intersection point is xi/yi, just in case...
  46298. //let yi = ((y3 - y4) * (x1 * y2 - y1 * x2) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d; // That's why I left it commented
  46299. if (xi < Math.min(x1, x2) || xi > Math.max(x1, x2))
  46300. return false;
  46301. if (xi < Math.min(x3, x4) || xi > Math.max(x3, x4))
  46302. return false;
  46303. return true;
  46304. };
  46305. Lines2D.prototype._updateMinMax = function (array, offset) {
  46306. if (offset >= array.length) {
  46307. return;
  46308. }
  46309. this._boundingMin.x = Math.min(this._boundingMin.x, array[offset]);
  46310. this._boundingMax.x = Math.max(this._boundingMax.x, array[offset]);
  46311. this._boundingMin.y = Math.min(this._boundingMin.y, array[offset + 1]);
  46312. this._boundingMax.y = Math.max(this._boundingMax.y, array[offset + 1]);
  46313. };
  46314. Lines2D.prototype._store = function (array, contour, index, max, p, n, halfThickness, borderThickness, detectFlip) {
  46315. var borderMode = borderThickness != null && !isNaN(borderThickness);
  46316. var off = index * (borderMode ? 8 : 4);
  46317. // Mandatory because we'll be out of bound in case of closed line, for the very last point (which is a duplicate of the first that we don't store in the vb)
  46318. if (off >= array.length) {
  46319. return;
  46320. }
  46321. // Store start/end normal, we need it for the cap construction
  46322. if (index === 0) {
  46323. this._perp(n, Lines2D._startDir);
  46324. }
  46325. else if (index === max - 1) {
  46326. this._perp(n, Lines2D._endDir);
  46327. Lines2D._endDir.x *= -1;
  46328. Lines2D._endDir.y *= -1;
  46329. }
  46330. var swap = false;
  46331. array[off + 0] = p.x + n.x * halfThickness;
  46332. array[off + 1] = p.y + n.y * halfThickness;
  46333. array[off + 2] = p.x + n.x * -halfThickness;
  46334. array[off + 3] = p.y + n.y * -halfThickness;
  46335. this._updateMinMax(array, off);
  46336. this._updateMinMax(array, off + 2);
  46337. // If an index is given we check if the two segments formed between [index+0;detectFlip+0] and [index+2;detectFlip+2] intersect themselves.
  46338. // It should not be the case, they should be parallel, so if they cross, we switch the order of storage to ensure we'll have parallel lines
  46339. if (detectFlip !== undefined) {
  46340. // Flip if intersect
  46341. var flipOff = detectFlip * (borderMode ? 8 : 4);
  46342. if (this._intersect(array[off + 0], array[off + 1], array[flipOff + 0], array[flipOff + 1], array[off + 2], array[off + 3], array[flipOff + 2], array[flipOff + 3])) {
  46343. swap = true;
  46344. var tps = array[off + 0];
  46345. array[off + 0] = array[off + 2];
  46346. array[off + 2] = tps;
  46347. tps = array[off + 1];
  46348. array[off + 1] = array[off + 3];
  46349. array[off + 3] = tps;
  46350. }
  46351. }
  46352. if (borderMode) {
  46353. var t = halfThickness + borderThickness;
  46354. array[off + 4] = p.x + n.x * (swap ? -t : t);
  46355. array[off + 5] = p.y + n.y * (swap ? -t : t);
  46356. array[off + 6] = p.x + n.x * (swap ? t : -t);
  46357. array[off + 7] = p.y + n.y * (swap ? t : -t);
  46358. this._updateMinMax(array, off + 4);
  46359. this._updateMinMax(array, off + 6);
  46360. }
  46361. if (contour) {
  46362. off += borderMode ? 4 : 0;
  46363. contour.push(new BABYLON.Vector2(array[off + 0], array[off + 1]));
  46364. contour.push(new BABYLON.Vector2(array[off + 2], array[off + 3]));
  46365. }
  46366. };
  46367. Lines2D.prototype._getCapSize = function (type, border) {
  46368. if (border === void 0) { border = false; }
  46369. var sd = Lines2D._roundCapSubDiv;
  46370. // If no array given, we call this to get the size
  46371. var vbsize = 0, ibsize = 0;
  46372. switch (type) {
  46373. case Lines2D.NoCap:
  46374. {
  46375. // If the line is not close and we're computing border, we add the size to generate the edge border
  46376. if (!this.closed && border) {
  46377. vbsize = 4;
  46378. ibsize = 6;
  46379. }
  46380. else {
  46381. vbsize = ibsize = 0;
  46382. }
  46383. break;
  46384. }
  46385. case Lines2D.RoundCap:
  46386. {
  46387. if (border) {
  46388. vbsize = sd;
  46389. ibsize = (sd - 2) * 3;
  46390. }
  46391. else {
  46392. vbsize = (sd / 2) + 1;
  46393. ibsize = (sd / 2) * 3;
  46394. }
  46395. break;
  46396. }
  46397. case Lines2D.ArrowCap:
  46398. {
  46399. if (border) {
  46400. vbsize = 12;
  46401. ibsize = 24;
  46402. }
  46403. else {
  46404. vbsize = 3;
  46405. ibsize = 3;
  46406. }
  46407. break;
  46408. }
  46409. case Lines2D.TriangleCap:
  46410. {
  46411. if (border) {
  46412. vbsize = 6;
  46413. ibsize = 12;
  46414. }
  46415. else {
  46416. vbsize = 3;
  46417. ibsize = 3;
  46418. }
  46419. break;
  46420. }
  46421. case Lines2D.DiamondAnchorCap:
  46422. {
  46423. if (border) {
  46424. vbsize = 10;
  46425. ibsize = 24;
  46426. }
  46427. else {
  46428. vbsize = 5;
  46429. ibsize = 9;
  46430. }
  46431. break;
  46432. }
  46433. case Lines2D.SquareAnchorCap:
  46434. {
  46435. if (border) {
  46436. vbsize = 12;
  46437. ibsize = 30;
  46438. }
  46439. else {
  46440. vbsize = 4;
  46441. ibsize = 6;
  46442. }
  46443. break;
  46444. }
  46445. case Lines2D.RoundAnchorCap:
  46446. {
  46447. if (border) {
  46448. vbsize = sd * 2;
  46449. ibsize = (sd - 1) * 6;
  46450. }
  46451. else {
  46452. vbsize = sd + 1;
  46453. ibsize = (sd + 1) * 3;
  46454. }
  46455. break;
  46456. }
  46457. }
  46458. return { vbsize: vbsize * 2, ibsize: ibsize };
  46459. };
  46460. Lines2D.prototype._storeVertex = function (vb, baseOffset, index, basePos, rotation, vertex, contour) {
  46461. var c = Math.cos(rotation);
  46462. var s = Math.sin(rotation);
  46463. Lines2D._tpsV.x = (c * vertex.x) + (-s * vertex.y) + basePos.x;
  46464. Lines2D._tpsV.y = (s * vertex.x) + (c * vertex.y) + basePos.y;
  46465. var offset = baseOffset + (index * 2);
  46466. vb[offset + 0] = Lines2D._tpsV.x;
  46467. vb[offset + 1] = Lines2D._tpsV.y;
  46468. if (contour) {
  46469. contour.push(Lines2D._tpsV.x);
  46470. contour.push(Lines2D._tpsV.y);
  46471. }
  46472. this._updateMinMax(vb, offset);
  46473. return (baseOffset + index * 2) / 2;
  46474. };
  46475. Lines2D.prototype._storeIndex = function (ib, baseOffset, index, vertexIndex) {
  46476. ib[baseOffset + index] = vertexIndex;
  46477. };
  46478. Lines2D.prototype._buildCap = function (vb, vbi, ib, ibi, pos, thickness, borderThickness, type, capDir, contour) {
  46479. // Compute the transformation from the direction of the cap to build relative to our default orientation [1;0] (our cap are by default pointing toward right, horizontal
  46480. var sd = Lines2D._roundCapSubDiv;
  46481. var dir = new BABYLON.Vector2(1, 0);
  46482. var angle = Math.atan2(capDir.y, capDir.x) - Math.atan2(dir.y, dir.x);
  46483. var ht = thickness / 2;
  46484. var t = thickness;
  46485. var borderMode = borderThickness != null;
  46486. var bt = borderThickness;
  46487. switch (type) {
  46488. case Lines2D.NoCap:
  46489. if (borderMode && !this.closed) {
  46490. var vi = 0;
  46491. var ii = 0;
  46492. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), contour);
  46493. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, ht + bt), contour);
  46494. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(bt, -(ht + bt)), contour);
  46495. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), contour);
  46496. this._storeIndex(ib, ibi, ii++, v1);
  46497. this._storeIndex(ib, ibi, ii++, v2);
  46498. this._storeIndex(ib, ibi, ii++, v3);
  46499. this._storeIndex(ib, ibi, ii++, v1);
  46500. this._storeIndex(ib, ibi, ii++, v3);
  46501. this._storeIndex(ib, ibi, ii++, v4);
  46502. }
  46503. break;
  46504. case Lines2D.ArrowCap:
  46505. ht *= 2;
  46506. case Lines2D.TriangleCap:
  46507. {
  46508. if (borderMode) {
  46509. var f = type === Lines2D.TriangleCap ? bt : Math.sqrt(bt * bt * 2);
  46510. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), null);
  46511. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), null);
  46512. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), null);
  46513. var v4 = this._storeVertex(vb, vbi, 3, pos, angle, new BABYLON.Vector2(0, ht + f), contour);
  46514. var v5 = this._storeVertex(vb, vbi, 4, pos, angle, new BABYLON.Vector2(ht + f, 0), contour);
  46515. var v6 = this._storeVertex(vb, vbi, 5, pos, angle, new BABYLON.Vector2(0, -(ht + f)), contour);
  46516. var ii = 0;
  46517. this._storeIndex(ib, ibi, ii++, v1);
  46518. this._storeIndex(ib, ibi, ii++, v4);
  46519. this._storeIndex(ib, ibi, ii++, v5);
  46520. this._storeIndex(ib, ibi, ii++, v1);
  46521. this._storeIndex(ib, ibi, ii++, v5);
  46522. this._storeIndex(ib, ibi, ii++, v2);
  46523. this._storeIndex(ib, ibi, ii++, v6);
  46524. this._storeIndex(ib, ibi, ii++, v3);
  46525. this._storeIndex(ib, ibi, ii++, v2);
  46526. this._storeIndex(ib, ibi, ii++, v6);
  46527. this._storeIndex(ib, ibi, ii++, v2);
  46528. this._storeIndex(ib, ibi, ii++, v5);
  46529. if (type === Lines2D.ArrowCap) {
  46530. var rht = thickness / 2;
  46531. var v10 = this._storeVertex(vb, vbi, 9, pos, angle, new BABYLON.Vector2(0, -(rht + bt)), null);
  46532. var v12 = this._storeVertex(vb, vbi, 11, pos, angle, new BABYLON.Vector2(-bt, -(ht + f)), contour);
  46533. var v11 = this._storeVertex(vb, vbi, 10, pos, angle, new BABYLON.Vector2(-bt, -(rht + bt)), contour);
  46534. var v7 = this._storeVertex(vb, vbi, 6, pos, angle, new BABYLON.Vector2(0, rht + bt), null);
  46535. var v8 = this._storeVertex(vb, vbi, 7, pos, angle, new BABYLON.Vector2(-bt, rht + bt), contour);
  46536. var v9 = this._storeVertex(vb, vbi, 8, pos, angle, new BABYLON.Vector2(-bt, ht + f), contour);
  46537. this._storeIndex(ib, ibi, ii++, v7);
  46538. this._storeIndex(ib, ibi, ii++, v8);
  46539. this._storeIndex(ib, ibi, ii++, v9);
  46540. this._storeIndex(ib, ibi, ii++, v7);
  46541. this._storeIndex(ib, ibi, ii++, v9);
  46542. this._storeIndex(ib, ibi, ii++, v4);
  46543. this._storeIndex(ib, ibi, ii++, v10);
  46544. this._storeIndex(ib, ibi, ii++, v12);
  46545. this._storeIndex(ib, ibi, ii++, v11);
  46546. this._storeIndex(ib, ibi, ii++, v10);
  46547. this._storeIndex(ib, ibi, ii++, v6);
  46548. this._storeIndex(ib, ibi, ii++, v12);
  46549. }
  46550. }
  46551. else {
  46552. var v1 = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, ht), contour);
  46553. var v2 = this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(ht, 0), contour);
  46554. var v3 = this._storeVertex(vb, vbi, 2, pos, angle, new BABYLON.Vector2(0, -ht), contour);
  46555. this._storeIndex(ib, ibi, 0, v1);
  46556. this._storeIndex(ib, ibi, 1, v2);
  46557. this._storeIndex(ib, ibi, 2, v3);
  46558. }
  46559. break;
  46560. }
  46561. case Lines2D.RoundCap:
  46562. {
  46563. if (borderMode) {
  46564. var curA = -Math.PI / 2;
  46565. var incA = Math.PI / (sd / 2 - 1);
  46566. var ii = 0;
  46567. for (var i = 0; i < (sd / 2); i++) {
  46568. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  46569. var v2 = this._storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * (ht + bt), Math.sin(curA) * (ht + bt)), contour);
  46570. if (i > 0) {
  46571. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46572. this._storeIndex(ib, ibi, ii++, v2 - 2);
  46573. this._storeIndex(ib, ibi, ii++, v2);
  46574. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46575. this._storeIndex(ib, ibi, ii++, v2);
  46576. this._storeIndex(ib, ibi, ii++, v1);
  46577. }
  46578. curA += incA;
  46579. }
  46580. }
  46581. else {
  46582. var c = this._storeVertex(vb, vbi, 0, pos, angle, new BABYLON.Vector2(0, 0), null);
  46583. var curA = -Math.PI / 2;
  46584. var incA = Math.PI / (sd / 2 - 1);
  46585. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), null);
  46586. curA += incA;
  46587. for (var i = 1; i < (sd / 2); i++) {
  46588. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(Math.cos(curA) * ht, Math.sin(curA) * ht), contour);
  46589. this._storeIndex(ib, ibi, i * 3 + 0, c);
  46590. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  46591. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  46592. curA += incA;
  46593. }
  46594. }
  46595. break;
  46596. }
  46597. case Lines2D.SquareAnchorCap:
  46598. {
  46599. var vi = 0;
  46600. var c = borderMode ? null : contour;
  46601. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, t), c);
  46602. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, t), c);
  46603. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2, -t), c);
  46604. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -t), c);
  46605. if (borderMode) {
  46606. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht + bt), null);
  46607. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, ht + bt), contour);
  46608. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, t + bt), contour);
  46609. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, t + bt), contour);
  46610. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(t * 2 + bt, -(t + bt)), contour);
  46611. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(t + bt)), contour);
  46612. var v11 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-bt, -(ht + bt)), contour);
  46613. var v12 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -(ht + bt)), null);
  46614. var ii = 0;
  46615. this._storeIndex(ib, ibi, ii++, v6);
  46616. this._storeIndex(ib, ibi, ii++, v1);
  46617. this._storeIndex(ib, ibi, ii++, v5);
  46618. this._storeIndex(ib, ibi, ii++, v6);
  46619. this._storeIndex(ib, ibi, ii++, v7);
  46620. this._storeIndex(ib, ibi, ii++, v1);
  46621. this._storeIndex(ib, ibi, ii++, v1);
  46622. this._storeIndex(ib, ibi, ii++, v7);
  46623. this._storeIndex(ib, ibi, ii++, v8);
  46624. this._storeIndex(ib, ibi, ii++, v1);
  46625. this._storeIndex(ib, ibi, ii++, v8);
  46626. this._storeIndex(ib, ibi, ii++, v2);
  46627. this._storeIndex(ib, ibi, ii++, v2);
  46628. this._storeIndex(ib, ibi, ii++, v8);
  46629. this._storeIndex(ib, ibi, ii++, v9);
  46630. this._storeIndex(ib, ibi, ii++, v2);
  46631. this._storeIndex(ib, ibi, ii++, v9);
  46632. this._storeIndex(ib, ibi, ii++, v3);
  46633. this._storeIndex(ib, ibi, ii++, v3);
  46634. this._storeIndex(ib, ibi, ii++, v9);
  46635. this._storeIndex(ib, ibi, ii++, v10);
  46636. this._storeIndex(ib, ibi, ii++, v3);
  46637. this._storeIndex(ib, ibi, ii++, v10);
  46638. this._storeIndex(ib, ibi, ii++, v4);
  46639. this._storeIndex(ib, ibi, ii++, v10);
  46640. this._storeIndex(ib, ibi, ii++, v11);
  46641. this._storeIndex(ib, ibi, ii++, v4);
  46642. this._storeIndex(ib, ibi, ii++, v11);
  46643. this._storeIndex(ib, ibi, ii++, v12);
  46644. this._storeIndex(ib, ibi, ii++, v4);
  46645. }
  46646. else {
  46647. this._storeIndex(ib, ibi, 0, v1);
  46648. this._storeIndex(ib, ibi, 1, v2);
  46649. this._storeIndex(ib, ibi, 2, v3);
  46650. this._storeIndex(ib, ibi, 3, v1);
  46651. this._storeIndex(ib, ibi, 4, v3);
  46652. this._storeIndex(ib, ibi, 5, v4);
  46653. }
  46654. break;
  46655. }
  46656. case Lines2D.RoundAnchorCap:
  46657. {
  46658. var cpos = Math.sqrt(t * t - ht * ht);
  46659. var center = new BABYLON.Vector2(cpos, 0);
  46660. var curA = BABYLON.Tools.ToRadians(-150);
  46661. var incA = BABYLON.Tools.ToRadians(300) / (sd - 1);
  46662. if (borderMode) {
  46663. var ii = 0;
  46664. for (var i = 0; i < sd; i++) {
  46665. var v1 = this._storeVertex(vb, vbi, i * 2 + 0, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  46666. var v2 = this._storeVertex(vb, vbi, i * 2 + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * (t + bt), Math.sin(curA) * (t + bt)), contour);
  46667. if (i > 0) {
  46668. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46669. this._storeIndex(ib, ibi, ii++, v2 - 2);
  46670. this._storeIndex(ib, ibi, ii++, v2);
  46671. this._storeIndex(ib, ibi, ii++, v1 - 2);
  46672. this._storeIndex(ib, ibi, ii++, v2);
  46673. this._storeIndex(ib, ibi, ii++, v1);
  46674. }
  46675. curA += incA;
  46676. }
  46677. }
  46678. else {
  46679. var c = this._storeVertex(vb, vbi, 0, pos, angle, center, null);
  46680. this._storeVertex(vb, vbi, 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), null);
  46681. curA += incA;
  46682. for (var i = 1; i < sd; i++) {
  46683. var v2 = this._storeVertex(vb, vbi, i + 1, pos, angle, new BABYLON.Vector2(cpos + Math.cos(curA) * t, Math.sin(curA) * t), contour);
  46684. this._storeIndex(ib, ibi, i * 3 + 0, c);
  46685. this._storeIndex(ib, ibi, i * 3 + 1, v2 - 1);
  46686. this._storeIndex(ib, ibi, i * 3 + 2, v2);
  46687. curA += incA;
  46688. }
  46689. this._storeIndex(ib, ibi, sd * 3 + 0, c);
  46690. this._storeIndex(ib, ibi, sd * 3 + 1, c + 1);
  46691. this._storeIndex(ib, ibi, sd * 3 + 2, c + sd);
  46692. }
  46693. break;
  46694. }
  46695. case Lines2D.DiamondAnchorCap:
  46696. {
  46697. var vi = 0;
  46698. var c = borderMode ? null : contour;
  46699. var v1 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, ht), c);
  46700. var v2 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t), c);
  46701. var v3 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3, 0), c);
  46702. var v4 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -t), c);
  46703. var v5 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(0, -ht), c);
  46704. if (borderMode) {
  46705. var f = Math.sqrt(bt * bt * 2);
  46706. var v6 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, ht), contour);
  46707. var v7 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, t + f), contour);
  46708. var v8 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht * 3 + f, 0), contour);
  46709. var v9 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(ht, -(t + f)), contour);
  46710. var v10 = this._storeVertex(vb, vbi, vi++, pos, angle, new BABYLON.Vector2(-f, -ht), contour);
  46711. var ii = 0;
  46712. this._storeIndex(ib, ibi, ii++, v6);
  46713. this._storeIndex(ib, ibi, ii++, v7);
  46714. this._storeIndex(ib, ibi, ii++, v1);
  46715. this._storeIndex(ib, ibi, ii++, v1);
  46716. this._storeIndex(ib, ibi, ii++, v7);
  46717. this._storeIndex(ib, ibi, ii++, v2);
  46718. this._storeIndex(ib, ibi, ii++, v2);
  46719. this._storeIndex(ib, ibi, ii++, v7);
  46720. this._storeIndex(ib, ibi, ii++, v8);
  46721. this._storeIndex(ib, ibi, ii++, v2);
  46722. this._storeIndex(ib, ibi, ii++, v8);
  46723. this._storeIndex(ib, ibi, ii++, v3);
  46724. this._storeIndex(ib, ibi, ii++, v3);
  46725. this._storeIndex(ib, ibi, ii++, v8);
  46726. this._storeIndex(ib, ibi, ii++, v9);
  46727. this._storeIndex(ib, ibi, ii++, v3);
  46728. this._storeIndex(ib, ibi, ii++, v9);
  46729. this._storeIndex(ib, ibi, ii++, v4);
  46730. this._storeIndex(ib, ibi, ii++, v4);
  46731. this._storeIndex(ib, ibi, ii++, v9);
  46732. this._storeIndex(ib, ibi, ii++, v10);
  46733. this._storeIndex(ib, ibi, ii++, v4);
  46734. this._storeIndex(ib, ibi, ii++, v10);
  46735. this._storeIndex(ib, ibi, ii++, v5);
  46736. }
  46737. else {
  46738. this._storeIndex(ib, ibi, 0, v1);
  46739. this._storeIndex(ib, ibi, 1, v2);
  46740. this._storeIndex(ib, ibi, 2, v3);
  46741. this._storeIndex(ib, ibi, 3, v1);
  46742. this._storeIndex(ib, ibi, 4, v3);
  46743. this._storeIndex(ib, ibi, 5, v5);
  46744. this._storeIndex(ib, ibi, 6, v5);
  46745. this._storeIndex(ib, ibi, 7, v3);
  46746. this._storeIndex(ib, ibi, 8, v4);
  46747. }
  46748. break;
  46749. }
  46750. }
  46751. return null;
  46752. };
  46753. Lines2D.prototype._buildLine = function (vb, contour, ht, bt) {
  46754. var lineA = BABYLON.Vector2.Zero();
  46755. var lineB = BABYLON.Vector2.Zero();
  46756. var tangent = BABYLON.Vector2.Zero();
  46757. var miter = BABYLON.Vector2.Zero();
  46758. var curNormal = null;
  46759. if (this.closed) {
  46760. this.points.push(this.points[0]);
  46761. }
  46762. var total = this.points.length;
  46763. for (var i = 1; i < total; i++) {
  46764. var last = this.points[i - 1];
  46765. var cur = this.points[i];
  46766. var next = (i < (this.points.length - 1)) ? this.points[i + 1] : null;
  46767. this._direction(cur, last, lineA);
  46768. if (!curNormal) {
  46769. curNormal = BABYLON.Vector2.Zero();
  46770. this._perp(lineA, curNormal);
  46771. }
  46772. if (i === 1) {
  46773. this._store(vb, contour, 0, total, this.points[0], curNormal, ht, bt);
  46774. }
  46775. if (!next) {
  46776. this._perp(lineA, curNormal);
  46777. this._store(vb, contour, i, total, this.points[i], curNormal, ht, bt, i - 1);
  46778. }
  46779. else {
  46780. this._direction(next, cur, lineB);
  46781. var miterLen = this._computeMiter(tangent, miter, lineA, lineB);
  46782. this._store(vb, contour, i, total, this.points[i], miter, miterLen * ht, miterLen * bt, i - 1);
  46783. }
  46784. }
  46785. if (this.points.length > 2 && this.closed) {
  46786. var last2 = this.points[total - 2];
  46787. var cur2 = this.points[0];
  46788. var next2 = this.points[1];
  46789. this._direction(cur2, last2, lineA);
  46790. this._direction(next2, cur2, lineB);
  46791. this._perp(lineA, curNormal);
  46792. var miterLen2 = this._computeMiter(tangent, miter, lineA, lineB);
  46793. this._store(vb, null, 0, total, this.points[0], miter, miterLen2 * ht, miterLen2 * bt, 1);
  46794. // Patch contour
  46795. if (contour) {
  46796. var off = (bt == null) ? 0 : 4;
  46797. contour[0].x = vb[off + 0];
  46798. contour[0].y = vb[off + 1];
  46799. contour[1].x = vb[off + 2];
  46800. contour[1].y = vb[off + 3];
  46801. }
  46802. }
  46803. // Remove the point we added at the beginning
  46804. if (this.closed) {
  46805. this.points.splice(total - 1);
  46806. }
  46807. };
  46808. // Methods for Lines building
  46809. ///////////////////////////////////////////////////////////////////////////////////
  46810. Lines2D.prototype.setupModelRenderCache = function (modelRenderCache) {
  46811. var renderCache = modelRenderCache;
  46812. var engine = this.owner.engine;
  46813. if (this._fillVB === null) {
  46814. this._computeLines2D();
  46815. }
  46816. // Need to create WebGL resources for fill part?
  46817. if (this.fill) {
  46818. renderCache.fillVB = engine.createVertexBuffer(this._fillVB);
  46819. renderCache.fillIB = engine.createIndexBuffer(this._fillIB);
  46820. renderCache.fillIndicesCount = this._fillIB.length;
  46821. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  46822. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, true);
  46823. if (ei) {
  46824. renderCache.effectFillInstanced = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  46825. }
  46826. // Get the non instanced version
  46827. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_FILLPARTID, ["position"], null, false);
  46828. renderCache.effectFill = engine.createEffect("lines2d", ei.attributes, ei.uniforms, [], ei.defines, null);
  46829. }
  46830. // Need to create WebGL resources for border part?
  46831. if (this.border) {
  46832. renderCache.borderVB = engine.createVertexBuffer(this._borderVB);
  46833. renderCache.borderIB = engine.createIndexBuffer(this._borderIB);
  46834. renderCache.borderIndicesCount = this._borderIB.length;
  46835. // Get the instanced version of the effect, if the engine does not support it, null is return and we'll only draw on by one
  46836. var ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, true);
  46837. if (ei) {
  46838. renderCache.effectBorderInstanced = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  46839. }
  46840. // Get the non instanced version
  46841. ei = this.getDataPartEffectInfo(BABYLON.Shape2D.SHAPE2D_BORDERPARTID, ["position"], null, false);
  46842. renderCache.effectBorder = engine.createEffect({ vertex: "lines2d", fragment: "lines2d" }, ei.attributes, ei.uniforms, [], ei.defines, null);
  46843. }
  46844. this._fillVB = null;
  46845. this._fillIB = null;
  46846. this._borderVB = null;
  46847. this._borderIB = null;
  46848. return renderCache;
  46849. };
  46850. Lines2D.prototype._computeLines2D = function () {
  46851. // Init min/max because their being computed here
  46852. this._boundingMin = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  46853. this._boundingMax = new BABYLON.Vector2(Number.MIN_VALUE, Number.MIN_VALUE);
  46854. var contour = new Array();
  46855. var startCapContour = new Array();
  46856. var endCapContour = new Array();
  46857. // Need to create WebGL resources for fill part?
  46858. if (this.fill) {
  46859. var startCapInfo = this._getCapSize(this.startCap);
  46860. var endCapInfo = this._getCapSize(this.endCap);
  46861. var count = this.points.length;
  46862. var vbSize = (count * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  46863. this._fillVB = new Float32Array(vbSize);
  46864. var vb = this._fillVB;
  46865. var ht = this.fillThickness / 2;
  46866. var total = this.points.length;
  46867. this._buildLine(vb, this.border ? null : contour, ht);
  46868. var max = total * 2;
  46869. var triCount = (count - (this.closed ? 0 : 1)) * 2;
  46870. this._fillIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  46871. var ib = this._fillIB;
  46872. for (var i = 0; i < triCount; i += 2) {
  46873. ib[i * 3 + 0] = i + 0;
  46874. ib[i * 3 + 1] = i + 1;
  46875. ib[i * 3 + 2] = (i + 2) % max;
  46876. ib[i * 3 + 3] = i + 1;
  46877. ib[i * 3 + 4] = (i + 3) % max;
  46878. ib[i * 3 + 5] = (i + 2) % max;
  46879. }
  46880. this._buildCap(vb, count * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, null, this.startCap, Lines2D._startDir, this.border ? null : startCapContour);
  46881. this._buildCap(vb, (count * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, null, this.endCap, Lines2D._endDir, this.border ? null : startCapContour);
  46882. }
  46883. // Need to create WebGL resources for border part?
  46884. if (this.border) {
  46885. var startCapInfo = this._getCapSize(this.startCap, true);
  46886. var endCapInfo = this._getCapSize(this.endCap, true);
  46887. var count = this.points.length;
  46888. var vbSize = (count * 2 * 2 * 2) + startCapInfo.vbsize + endCapInfo.vbsize;
  46889. this._borderVB = new Float32Array(vbSize);
  46890. var vb = this._borderVB;
  46891. var ht = this.fillThickness / 2;
  46892. var bt = this.borderThickness;
  46893. var total = this.points.length;
  46894. this._buildLine(vb, contour, ht, bt);
  46895. var max = total * 2 * 2;
  46896. var triCount = (count - (this.closed ? 0 : 1)) * 2 * 2;
  46897. this._borderIB = new Float32Array(triCount * 3 + startCapInfo.ibsize + endCapInfo.ibsize);
  46898. var ib = this._borderIB;
  46899. for (var i = 0; i < triCount; i += 4) {
  46900. ib[i * 3 + 0] = i + 0;
  46901. ib[i * 3 + 1] = i + 2;
  46902. ib[i * 3 + 2] = (i + 6) % max;
  46903. ib[i * 3 + 3] = i + 0;
  46904. ib[i * 3 + 4] = (i + 6) % max;
  46905. ib[i * 3 + 5] = (i + 4) % max;
  46906. ib[i * 3 + 6] = i + 3;
  46907. ib[i * 3 + 7] = i + 1;
  46908. ib[i * 3 + 8] = (i + 5) % max;
  46909. ib[i * 3 + 9] = i + 3;
  46910. ib[i * 3 + 10] = (i + 5) % max;
  46911. ib[i * 3 + 11] = (i + 7) % max;
  46912. }
  46913. this._buildCap(vb, count * 2 * 2 * 2, ib, triCount * 3, this.points[0], this.fillThickness, this.borderThickness, this.startCap, Lines2D._startDir, startCapContour);
  46914. this._buildCap(vb, (count * 2 * 2 * 2) + startCapInfo.vbsize, ib, (triCount * 3) + startCapInfo.ibsize, this.points[total - 1], this.fillThickness, this.borderThickness, this.endCap, Lines2D._endDir, endCapContour);
  46915. }
  46916. this._contour = contour;
  46917. if (startCapContour.length > 0) {
  46918. var startCapTri = Earcut.earcut(startCapContour, null, 2);
  46919. this._startCapTriIndices = startCapTri;
  46920. this._startCapContour = startCapContour;
  46921. }
  46922. else {
  46923. this._startCapTriIndices = null;
  46924. this._startCapContour = null;
  46925. }
  46926. if (endCapContour.length > 0) {
  46927. var endCapTri = Earcut.earcut(endCapContour, null, 2);
  46928. this._endCapContour = endCapContour;
  46929. this._endCapTriIndices = endCapTri;
  46930. }
  46931. else {
  46932. this._endCapContour = null;
  46933. this._endCapTriIndices = null;
  46934. }
  46935. var bs = this._boundingMax.subtract(this._boundingMin);
  46936. this._size.width = bs.x;
  46937. this._size.height = bs.y;
  46938. };
  46939. Object.defineProperty(Lines2D.prototype, "size", {
  46940. get: function () {
  46941. if (this._size == null) {
  46942. this._computeLines2D();
  46943. }
  46944. return this._size;
  46945. },
  46946. enumerable: true,
  46947. configurable: true
  46948. });
  46949. Lines2D.prototype.createInstanceDataParts = function () {
  46950. var res = new Array();
  46951. if (this.border) {
  46952. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_BORDERPARTID));
  46953. }
  46954. if (this.fill) {
  46955. res.push(new Lines2DInstanceData(BABYLON.Shape2D.SHAPE2D_FILLPARTID));
  46956. }
  46957. return res;
  46958. };
  46959. Lines2D.prototype.refreshInstanceDataPart = function (part) {
  46960. if (!_super.prototype.refreshInstanceDataPart.call(this, part)) {
  46961. return false;
  46962. }
  46963. if (part.id === BABYLON.Shape2D.SHAPE2D_BORDERPARTID) {
  46964. var d = part;
  46965. if (this.border instanceof BABYLON.GradientColorBrush2D) {
  46966. d.boundingMin = this.boundingMin;
  46967. d.boundingMax = this.boundingMax;
  46968. }
  46969. }
  46970. else if (part.id === BABYLON.Shape2D.SHAPE2D_FILLPARTID) {
  46971. var d = part;
  46972. if (this.fill instanceof BABYLON.GradientColorBrush2D) {
  46973. d.boundingMin = this.boundingMin;
  46974. d.boundingMax = this.boundingMax;
  46975. }
  46976. }
  46977. return true;
  46978. };
  46979. Lines2D._prevA = BABYLON.Vector2.Zero();
  46980. Lines2D._prevB = BABYLON.Vector2.Zero();
  46981. Lines2D._curA = BABYLON.Vector2.Zero();
  46982. Lines2D._curB = BABYLON.Vector2.Zero();
  46983. Lines2D._miterTps = BABYLON.Vector2.Zero();
  46984. Lines2D._startDir = BABYLON.Vector2.Zero();
  46985. Lines2D._endDir = BABYLON.Vector2.Zero();
  46986. Lines2D._tpsV = BABYLON.Vector2.Zero();
  46987. Lines2D._noCap = 0;
  46988. Lines2D._roundCap = 1;
  46989. Lines2D._triangleCap = 2;
  46990. Lines2D._squareAnchorCap = 3;
  46991. Lines2D._roundAnchorCap = 4;
  46992. Lines2D._diamondAnchorCap = 5;
  46993. Lines2D._arrowCap = 6;
  46994. Lines2D._roundCapSubDiv = 36;
  46995. __decorate([
  46996. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 1, function (pi) { return Lines2D.pointsProperty = pi; })
  46997. ], Lines2D.prototype, "points", null);
  46998. __decorate([
  46999. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 2, function (pi) { return Lines2D.fillThicknessProperty = pi; })
  47000. ], Lines2D.prototype, "fillThickness", null);
  47001. __decorate([
  47002. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 3, function (pi) { return Lines2D.closedProperty = pi; })
  47003. ], Lines2D.prototype, "closed", null);
  47004. __decorate([
  47005. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 4, function (pi) { return Lines2D.startCapProperty = pi; })
  47006. ], Lines2D.prototype, "startCap", null);
  47007. __decorate([
  47008. BABYLON.modelLevelProperty(BABYLON.Shape2D.SHAPE2D_PROPCOUNT + 5, function (pi) { return Lines2D.endCapProperty = pi; })
  47009. ], Lines2D.prototype, "endCap", null);
  47010. Lines2D = __decorate([
  47011. BABYLON.className("Lines2D")
  47012. ], Lines2D);
  47013. return Lines2D;
  47014. }(BABYLON.Shape2D));
  47015. BABYLON.Lines2D = Lines2D;
  47016. })(BABYLON || (BABYLON = {}));
  47017. var BABYLON;
  47018. (function (BABYLON) {
  47019. // This class contains data that lifetime is bounding to the Babylon Engine object
  47020. var Canvas2DEngineBoundData = (function () {
  47021. function Canvas2DEngineBoundData() {
  47022. this._modelCache = new BABYLON.StringDictionary();
  47023. }
  47024. Canvas2DEngineBoundData.prototype.GetOrAddModelCache = function (key, factory) {
  47025. return this._modelCache.getOrAddWithFactory(key, factory);
  47026. };
  47027. Canvas2DEngineBoundData.prototype.DisposeModelRenderCache = function (modelRenderCache) {
  47028. if (!modelRenderCache.isDisposed) {
  47029. return false;
  47030. }
  47031. this._modelCache.remove(modelRenderCache.modelKey);
  47032. return true;
  47033. };
  47034. return Canvas2DEngineBoundData;
  47035. }());
  47036. BABYLON.Canvas2DEngineBoundData = Canvas2DEngineBoundData;
  47037. var Canvas2D = (function (_super) {
  47038. __extends(Canvas2D, _super);
  47039. function Canvas2D(scene, settings) {
  47040. var _this = this;
  47041. _super.call(this, settings);
  47042. /**
  47043. * If you set your own WorldSpaceNode to display the Canvas2D you have to provide your own implementation of this method which computes the local position in the Canvas based on the given 3D World one.
  47044. * Beware that you have to take under consideration the origin in your calculations! Good luck!
  47045. */
  47046. this.worldSpaceToNodeLocal = function (worldPos) {
  47047. var node = _this._worldSpaceNode;
  47048. if (!node) {
  47049. return;
  47050. }
  47051. var mtx = node.getWorldMatrix().clone();
  47052. mtx.invert();
  47053. var v = BABYLON.Vector3.TransformCoordinates(worldPos, mtx);
  47054. var res = new BABYLON.Vector2(v.x, v.y);
  47055. var size = _this.actualSize;
  47056. res.x += size.width * 0.5; // res is centered, make it relative to bottom/left
  47057. res.y += size.height * 0.5;
  47058. return res;
  47059. };
  47060. /**
  47061. * If you use a custom WorldSpaceCanvasNode you have to override this property to update the UV of your object to reflect the changes due to a resizing of the cached bitmap
  47062. */
  47063. this.worldSpaceCacheChanged = function () {
  47064. var plane = _this.worldSpaceCanvasNode;
  47065. var vd = BABYLON.VertexData.ExtractFromMesh(plane); //new VertexData();
  47066. vd.uvs = new Float32Array(8);
  47067. var material = plane.material;
  47068. var tex = _this._renderableData._cacheTexture;
  47069. if (material.diffuseTexture !== tex) {
  47070. material.diffuseTexture = tex;
  47071. tex.hasAlpha = true;
  47072. }
  47073. var nodeuv = _this._renderableData._cacheNodeUVs;
  47074. for (var i = 0; i < 4; i++) {
  47075. vd.uvs[i * 2 + 0] = nodeuv[i].x;
  47076. vd.uvs[i * 2 + 1] = nodeuv[i].y;
  47077. }
  47078. vd.applyToMesh(plane);
  47079. };
  47080. this._notifDebugMode = false;
  47081. this._mapCounter = 0;
  47082. this._drawCallsOpaqueCounter = new BABYLON.PerfCounter();
  47083. this._drawCallsAlphaTestCounter = new BABYLON.PerfCounter();
  47084. this._drawCallsTransparentCounter = new BABYLON.PerfCounter();
  47085. this._groupRenderCounter = new BABYLON.PerfCounter();
  47086. this._updateTransparentDataCounter = new BABYLON.PerfCounter();
  47087. this._cachedGroupRenderCounter = new BABYLON.PerfCounter();
  47088. this._updateCachedStateCounter = new BABYLON.PerfCounter();
  47089. this._updateLayoutCounter = new BABYLON.PerfCounter();
  47090. this._updatePositioningCounter = new BABYLON.PerfCounter();
  47091. this._updateLocalTransformCounter = new BABYLON.PerfCounter();
  47092. this._updateGlobalTransformCounter = new BABYLON.PerfCounter();
  47093. this._boundingInfoRecomputeCounter = new BABYLON.PerfCounter();
  47094. this._profileInfoText = null;
  47095. BABYLON.Prim2DBase._isCanvasInit = false;
  47096. if (!settings) {
  47097. settings = {};
  47098. }
  47099. if (this._cachingStrategy !== Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  47100. this._background = new BABYLON.Rectangle2D({ parent: this, id: "###CANVAS BACKGROUND###", size: settings.size }); //TODO CHECK when size is null
  47101. this._background.zOrder = 1.0;
  47102. this._background.isPickable = false;
  47103. this._background.origin = BABYLON.Vector2.Zero();
  47104. this._background.levelVisible = false;
  47105. if (settings.backgroundRoundRadius != null) {
  47106. this.backgroundRoundRadius = settings.backgroundRoundRadius;
  47107. }
  47108. if (settings.backgroundBorder != null) {
  47109. if (typeof (settings.backgroundBorder) === "string") {
  47110. this.backgroundBorder = Canvas2D.GetBrushFromString(settings.backgroundBorder);
  47111. }
  47112. else {
  47113. this.backgroundBorder = settings.backgroundBorder;
  47114. }
  47115. }
  47116. if (settings.backgroundBorderThickNess != null) {
  47117. this.backgroundBorderThickness = settings.backgroundBorderThickNess;
  47118. }
  47119. if (settings.backgroundFill != null) {
  47120. if (typeof (settings.backgroundFill) === "string") {
  47121. this.backgroundFill = Canvas2D.GetBrushFromString(settings.backgroundFill);
  47122. }
  47123. else {
  47124. this.backgroundFill = settings.backgroundFill;
  47125. }
  47126. }
  47127. this._background._patchHierarchy(this);
  47128. }
  47129. var engine = scene.getEngine();
  47130. this.__engineData = engine.getOrAddExternalDataWithFactory("__BJSCANVAS2D__", function (k) { return new Canvas2DEngineBoundData(); });
  47131. this._primPointerInfo = new BABYLON.PrimitivePointerInfo();
  47132. this._capturedPointers = new BABYLON.StringDictionary();
  47133. this._pickStartingPosition = BABYLON.Vector2.Zero();
  47134. this._hierarchyLevelMaxSiblingCount = 50;
  47135. this._hierarchyDepth = 0;
  47136. this._zOrder = 0;
  47137. this._zMax = 1;
  47138. this._scene = scene;
  47139. this._engine = engine;
  47140. this._renderingSize = new BABYLON.Size(0, 0);
  47141. this._trackedGroups = new Array();
  47142. this._maxAdaptiveWorldSpaceCanvasSize = null;
  47143. this._groupCacheMaps = new BABYLON.StringDictionary();
  47144. this._patchHierarchy(this);
  47145. var enableInteraction = (settings.enableInteraction == null) ? true : settings.enableInteraction;
  47146. this._fitRenderingDevice = !settings.size;
  47147. if (!settings.size) {
  47148. settings.size = new BABYLON.Size(engine.getRenderWidth(), engine.getRenderHeight());
  47149. }
  47150. // Register scene dispose to also dispose the canvas when it'll happens
  47151. scene.onDisposeObservable.add(function (d, s) {
  47152. _this.dispose();
  47153. });
  47154. if (this._isScreenSpace) {
  47155. this._afterRenderObserver = this._scene.onAfterRenderObservable.add(function (d, s) {
  47156. _this._engine.clear(null, false, true, true);
  47157. _this._render();
  47158. });
  47159. }
  47160. else {
  47161. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function (d, s) {
  47162. _this._render();
  47163. });
  47164. }
  47165. this._supprtInstancedArray = this._engine.getCaps().instancedArrays !== null;
  47166. //this._supprtInstancedArray = false; // TODO REMOVE!!!
  47167. this._setupInteraction(enableInteraction);
  47168. }
  47169. Object.defineProperty(Canvas2D.prototype, "drawCallsOpaqueCounter", {
  47170. get: function () {
  47171. return this._drawCallsOpaqueCounter;
  47172. },
  47173. enumerable: true,
  47174. configurable: true
  47175. });
  47176. Object.defineProperty(Canvas2D.prototype, "drawCallsAlphaTestCounter", {
  47177. get: function () {
  47178. return this._drawCallsAlphaTestCounter;
  47179. },
  47180. enumerable: true,
  47181. configurable: true
  47182. });
  47183. Object.defineProperty(Canvas2D.prototype, "drawCallsTransparentCounter", {
  47184. get: function () {
  47185. return this._drawCallsTransparentCounter;
  47186. },
  47187. enumerable: true,
  47188. configurable: true
  47189. });
  47190. Object.defineProperty(Canvas2D.prototype, "groupRenderCounter", {
  47191. get: function () {
  47192. return this._groupRenderCounter;
  47193. },
  47194. enumerable: true,
  47195. configurable: true
  47196. });
  47197. Object.defineProperty(Canvas2D.prototype, "updateTransparentDataCounter", {
  47198. get: function () {
  47199. return this._updateTransparentDataCounter;
  47200. },
  47201. enumerable: true,
  47202. configurable: true
  47203. });
  47204. Object.defineProperty(Canvas2D.prototype, "cachedGroupRenderCounter", {
  47205. get: function () {
  47206. return this._cachedGroupRenderCounter;
  47207. },
  47208. enumerable: true,
  47209. configurable: true
  47210. });
  47211. Object.defineProperty(Canvas2D.prototype, "updateCachedStateCounter", {
  47212. get: function () {
  47213. return this._updateCachedStateCounter;
  47214. },
  47215. enumerable: true,
  47216. configurable: true
  47217. });
  47218. Object.defineProperty(Canvas2D.prototype, "updateLayoutCounter", {
  47219. get: function () {
  47220. return this._updateLayoutCounter;
  47221. },
  47222. enumerable: true,
  47223. configurable: true
  47224. });
  47225. Object.defineProperty(Canvas2D.prototype, "updatePositioningCounter", {
  47226. get: function () {
  47227. return this._updatePositioningCounter;
  47228. },
  47229. enumerable: true,
  47230. configurable: true
  47231. });
  47232. Object.defineProperty(Canvas2D.prototype, "updateLocalTransformCounter", {
  47233. get: function () {
  47234. return this._updateLocalTransformCounter;
  47235. },
  47236. enumerable: true,
  47237. configurable: true
  47238. });
  47239. Object.defineProperty(Canvas2D.prototype, "updateGlobalTransformCounter", {
  47240. get: function () {
  47241. return this._updateGlobalTransformCounter;
  47242. },
  47243. enumerable: true,
  47244. configurable: true
  47245. });
  47246. Object.defineProperty(Canvas2D.prototype, "boundingInfoRecomputeCounter", {
  47247. get: function () {
  47248. return this._boundingInfoRecomputeCounter;
  47249. },
  47250. enumerable: true,
  47251. configurable: true
  47252. });
  47253. Canvas2D.prototype._canvasPreInit = function (settings) {
  47254. var cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_DONTCACHE : settings.cachingStrategy;
  47255. this._cachingStrategy = cachingStrategy;
  47256. this._isScreenSpace = (settings.isScreenSpace == null) ? true : settings.isScreenSpace;
  47257. };
  47258. Canvas2D.prototype._setupInteraction = function (enable) {
  47259. var _this = this;
  47260. // No change detection
  47261. if (enable === this._interactionEnabled) {
  47262. return;
  47263. }
  47264. // Set the new state
  47265. this._interactionEnabled = enable;
  47266. // ScreenSpace mode
  47267. if (this._isScreenSpace) {
  47268. // Disable interaction
  47269. if (!enable) {
  47270. if (this._scenePrePointerObserver) {
  47271. this.scene.onPrePointerObservable.remove(this._scenePrePointerObserver);
  47272. this._scenePrePointerObserver = null;
  47273. }
  47274. return;
  47275. }
  47276. // Enable Interaction
  47277. // Register the observable
  47278. this._scenePrePointerObserver = this.scene.onPrePointerObservable.add(function (e, s) {
  47279. if (_this.isVisible === false) {
  47280. return;
  47281. }
  47282. var hs = 1 / _this.engine.getHardwareScalingLevel();
  47283. var localPos = e.localPosition.multiplyByFloats(hs, hs);
  47284. _this._handlePointerEventForInteraction(e, localPos, s);
  47285. });
  47286. }
  47287. else {
  47288. var scene = this.scene;
  47289. if (enable) {
  47290. scene.constantlyUpdateMeshUnderPointer = true;
  47291. this._scenePointerObserver = scene.onPointerObservable.add(function (e, s) {
  47292. if (_this.isVisible === false) {
  47293. return;
  47294. }
  47295. if (e.pickInfo.hit && e.pickInfo.pickedMesh === _this._worldSpaceNode && _this.worldSpaceToNodeLocal) {
  47296. var localPos = _this.worldSpaceToNodeLocal(e.pickInfo.pickedPoint);
  47297. _this._handlePointerEventForInteraction(e, localPos, s);
  47298. }
  47299. });
  47300. }
  47301. else {
  47302. if (this._scenePointerObserver) {
  47303. this.scene.onPointerObservable.remove(this._scenePointerObserver);
  47304. this._scenePointerObserver = null;
  47305. }
  47306. }
  47307. }
  47308. };
  47309. /**
  47310. * Internal method, you should use the Prim2DBase version instead
  47311. */
  47312. Canvas2D.prototype._setPointerCapture = function (pointerId, primitive) {
  47313. if (this.isPointerCaptured(pointerId)) {
  47314. return false;
  47315. }
  47316. // Try to capture the pointer on the HTML side
  47317. try {
  47318. this.engine.getRenderingCanvas().setPointerCapture(pointerId);
  47319. }
  47320. catch (e) {
  47321. }
  47322. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  47323. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerGotCapture, null);
  47324. this._capturedPointers.add(pointerId.toString(), primitive);
  47325. return true;
  47326. };
  47327. /**
  47328. * Internal method, you should use the Prim2DBase version instead
  47329. */
  47330. Canvas2D.prototype._releasePointerCapture = function (pointerId, primitive) {
  47331. if (this._capturedPointers.get(pointerId.toString()) !== primitive) {
  47332. return false;
  47333. }
  47334. // Try to release the pointer on the HTML side
  47335. try {
  47336. this.engine.getRenderingCanvas().releasePointerCapture(pointerId);
  47337. }
  47338. catch (e) {
  47339. }
  47340. this._primPointerInfo.updateRelatedTarget(primitive, BABYLON.Vector2.Zero());
  47341. this._bubbleNotifyPrimPointerObserver(primitive, BABYLON.PrimitivePointerInfo.PointerLostCapture, null);
  47342. this._capturedPointers.remove(pointerId.toString());
  47343. return true;
  47344. };
  47345. /**
  47346. * Determine if the given pointer is captured or not
  47347. * @param pointerId the Id of the pointer
  47348. * @return true if it's captured, false otherwise
  47349. */
  47350. Canvas2D.prototype.isPointerCaptured = function (pointerId) {
  47351. return this._capturedPointers.contains(pointerId.toString());
  47352. };
  47353. Canvas2D.prototype.getCapturedPrimitive = function (pointerId) {
  47354. // Avoid unnecessary lookup
  47355. if (this._capturedPointers.count === 0) {
  47356. return null;
  47357. }
  47358. return this._capturedPointers.get(pointerId.toString());
  47359. };
  47360. Canvas2D.prototype._handlePointerEventForInteraction = function (eventData, localPosition, eventState) {
  47361. // Dispose check
  47362. if (this.isDisposed) {
  47363. return;
  47364. }
  47365. // Update the this._primPointerInfo structure we'll send to observers using the PointerEvent data
  47366. this._updatePointerInfo(eventData, localPosition);
  47367. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  47368. // Make sure the intersection list is up to date, we maintain this list either in response of a mouse event (here) or before rendering the canvas.
  47369. // Why before rendering the canvas? because some primitives may move and get away/under the mouse cursor (which is not moving). So we need to update at both location in order to always have an accurate list, which is needed for the hover state change.
  47370. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, capturedPrim !== null);
  47371. // Update the over status, same as above, it's could be done here or during rendering, but will be performed only once per render frame
  47372. this._updateOverStatus();
  47373. // Check if we have nothing to raise
  47374. if (!this._actualOverPrimitive && !capturedPrim) {
  47375. return;
  47376. }
  47377. // Update the relatedTarget info with the over primitive or the captured one (if any)
  47378. var targetPrim = capturedPrim || this._actualOverPrimitive.prim;
  47379. var targetPointerPos = capturedPrim ? this._primPointerInfo.canvasPointerPos.subtract(new BABYLON.Vector2(targetPrim.globalTransform.m[12], targetPrim.globalTransform.m[13])) : this._actualOverPrimitive.intersectionLocation;
  47380. this._primPointerInfo.updateRelatedTarget(targetPrim, targetPointerPos);
  47381. // Analyze the pointer event type and fire proper events on the primitive
  47382. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  47383. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMouseWheel, eventData.event);
  47384. }
  47385. else if (eventData.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47386. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerMove, eventData.event);
  47387. }
  47388. else if (eventData.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  47389. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerDown, eventData.event);
  47390. }
  47391. else if (eventData.type === BABYLON.PointerEventTypes.POINTERUP) {
  47392. this._bubbleNotifyPrimPointerObserver(targetPrim, BABYLON.PrimitivePointerInfo.PointerUp, eventData.event);
  47393. }
  47394. };
  47395. Canvas2D.prototype._updatePointerInfo = function (eventData, localPosition) {
  47396. var pii = this._primPointerInfo;
  47397. if (!pii.canvasPointerPos) {
  47398. pii.canvasPointerPos = BABYLON.Vector2.Zero();
  47399. }
  47400. var camera = this._scene.cameraToUseForPointers || this._scene.activeCamera;
  47401. var engine = this._scene.getEngine();
  47402. if (this._isScreenSpace) {
  47403. var cameraViewport = camera.viewport;
  47404. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47405. // Moving coordinates to local viewport world
  47406. var x = localPosition.x - viewport.x;
  47407. var y = localPosition.y - viewport.y;
  47408. pii.canvasPointerPos.x = x - this.actualPosition.x;
  47409. pii.canvasPointerPos.y = engine.getRenderHeight() - y - this.actualPosition.y;
  47410. }
  47411. else {
  47412. pii.canvasPointerPos.x = localPosition.x;
  47413. pii.canvasPointerPos.y = localPosition.y;
  47414. }
  47415. pii.mouseWheelDelta = 0;
  47416. if (eventData.type === BABYLON.PointerEventTypes.POINTERWHEEL) {
  47417. var event = eventData.event;
  47418. if (event.wheelDelta) {
  47419. pii.mouseWheelDelta = event.wheelDelta / (BABYLON.PrimitivePointerInfo.MouseWheelPrecision * 40);
  47420. }
  47421. else if (event.detail) {
  47422. pii.mouseWheelDelta = -event.detail / BABYLON.PrimitivePointerInfo.MouseWheelPrecision;
  47423. }
  47424. }
  47425. else {
  47426. var pe = eventData.event;
  47427. pii.ctrlKey = pe.ctrlKey;
  47428. pii.altKey = pe.altKey;
  47429. pii.shiftKey = pe.shiftKey;
  47430. pii.metaKey = pe.metaKey;
  47431. pii.button = pe.button;
  47432. pii.buttons = pe.buttons;
  47433. pii.pointerId = pe.pointerId;
  47434. pii.width = pe.width;
  47435. pii.height = pe.height;
  47436. pii.presssure = pe.pressure;
  47437. pii.tilt.x = pe.tiltX;
  47438. pii.tilt.y = pe.tiltY;
  47439. pii.isCaptured = this.getCapturedPrimitive(pe.pointerId) !== null;
  47440. }
  47441. };
  47442. Canvas2D.prototype._updateIntersectionList = function (mouseLocalPos, isCapture) {
  47443. if (this.scene.getRenderId() === this._intersectionRenderId) {
  47444. return;
  47445. }
  47446. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  47447. if (!this._globalTransform) {
  47448. this.updateCachedStates(true);
  47449. }
  47450. var ii = Canvas2D._interInfo;
  47451. ii.pickPosition.x = mouseLocalPos.x;
  47452. ii.pickPosition.y = mouseLocalPos.y;
  47453. ii.findFirstOnly = false;
  47454. // Fast rejection: test if the mouse pointer is outside the canvas's bounding Info
  47455. if (!isCapture && !this.levelBoundingInfo.doesIntersect(ii.pickPosition)) {
  47456. this._previousIntersectionList = this._actualIntersectionList;
  47457. this._actualIntersectionList = null;
  47458. this._previousOverPrimitive = this._actualOverPrimitive;
  47459. this._actualOverPrimitive = null;
  47460. return;
  47461. }
  47462. this.intersect(ii);
  47463. this._previousIntersectionList = this._actualIntersectionList;
  47464. this._actualIntersectionList = ii.intersectedPrimitives;
  47465. this._previousOverPrimitive = this._actualOverPrimitive;
  47466. this._actualOverPrimitive = ii.topMostIntersectedPrimitive;
  47467. this._intersectionRenderId = this.scene.getRenderId();
  47468. };
  47469. // Based on the previousIntersectionList and the actualInstersectionList we can determined which primitives are being hover state or loosing it
  47470. Canvas2D.prototype._updateOverStatus = function () {
  47471. if ((this.scene.getRenderId() === this._hoverStatusRenderId) || !this._previousIntersectionList || !this._actualIntersectionList) {
  47472. return;
  47473. }
  47474. // Detect a change of over
  47475. var prevPrim = this._previousOverPrimitive ? this._previousOverPrimitive.prim : null;
  47476. var actualPrim = this._actualOverPrimitive ? this._actualOverPrimitive.prim : null;
  47477. if (prevPrim !== actualPrim) {
  47478. // Detect if the current pointer is captured, only fire event if they belong to the capture primitive
  47479. var capturedPrim = this.getCapturedPrimitive(this._primPointerInfo.pointerId);
  47480. // Notify the previous "over" prim that the pointer is no longer over it
  47481. if ((capturedPrim && capturedPrim === prevPrim) || (!capturedPrim && prevPrim)) {
  47482. this._primPointerInfo.updateRelatedTarget(prevPrim, this._previousOverPrimitive.intersectionLocation);
  47483. this._bubbleNotifyPrimPointerObserver(prevPrim, BABYLON.PrimitivePointerInfo.PointerOut, null);
  47484. }
  47485. // Notify the new "over" prim that the pointer is over it
  47486. if ((capturedPrim && capturedPrim === actualPrim) || (!capturedPrim && actualPrim)) {
  47487. this._primPointerInfo.updateRelatedTarget(actualPrim, this._actualOverPrimitive.intersectionLocation);
  47488. this._bubbleNotifyPrimPointerObserver(actualPrim, BABYLON.PrimitivePointerInfo.PointerOver, null);
  47489. }
  47490. }
  47491. this._hoverStatusRenderId = this.scene.getRenderId();
  47492. };
  47493. Canvas2D.prototype._updatePrimPointerPos = function (prim) {
  47494. if (this._primPointerInfo.isCaptured) {
  47495. this._primPointerInfo.primitivePointerPos = this._primPointerInfo.relatedTargetPointerPos;
  47496. }
  47497. else {
  47498. for (var _i = 0, _a = this._actualIntersectionList; _i < _a.length; _i++) {
  47499. var pii = _a[_i];
  47500. if (pii.prim === prim) {
  47501. this._primPointerInfo.primitivePointerPos = pii.intersectionLocation;
  47502. return;
  47503. }
  47504. }
  47505. }
  47506. };
  47507. Canvas2D.prototype._debugExecObserver = function (prim, mask) {
  47508. if (!this._notifDebugMode) {
  47509. return;
  47510. }
  47511. var debug = "";
  47512. for (var i = 0; i < prim.hierarchyDepth; i++) {
  47513. debug += " ";
  47514. }
  47515. var pii = this._primPointerInfo;
  47516. debug += "[RID:" + this.scene.getRenderId() + "] [" + prim.hierarchyDepth + "] event:" + BABYLON.PrimitivePointerInfo.getEventTypeName(mask) + ", id: " + prim.id + " (" + BABYLON.Tools.getClassName(prim) + "), primPos: " + pii.primitivePointerPos.toString() + ", canvasPos: " + pii.canvasPointerPos.toString();
  47517. console.log(debug);
  47518. };
  47519. Canvas2D.prototype._bubbleNotifyPrimPointerObserver = function (prim, mask, eventData) {
  47520. var ppi = this._primPointerInfo;
  47521. // In case of PointerOver/Out we will first notify the parent with PointerEnter/Leave
  47522. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) !== 0) {
  47523. this._notifParents(prim, mask);
  47524. }
  47525. var bubbleCancelled = false;
  47526. var cur = prim;
  47527. while (cur) {
  47528. // Only trigger the observers if the primitive is intersected (except for out)
  47529. if (!bubbleCancelled) {
  47530. this._updatePrimPointerPos(cur);
  47531. // Exec the observers
  47532. this._debugExecObserver(cur, mask);
  47533. cur._pointerEventObservable.notifyObservers(ppi, mask);
  47534. this._triggerActionManager(cur, ppi, mask, eventData);
  47535. // Bubble canceled? If we're not executing PointerOver or PointerOut, quit immediately
  47536. // If it's PointerOver/Out we have to trigger PointerEnter/Leave no matter what
  47537. if (ppi.cancelBubble) {
  47538. if ((mask & (BABYLON.PrimitivePointerInfo.PointerOver | BABYLON.PrimitivePointerInfo.PointerOut)) === 0) {
  47539. return;
  47540. }
  47541. // We're dealing with PointerOver/Out, let's keep looping to fire PointerEnter/Leave, but not Over/Out anymore
  47542. bubbleCancelled = true;
  47543. }
  47544. }
  47545. // If bubble is cancel we didn't update the Primitive Pointer Pos yet, let's do it
  47546. if (bubbleCancelled) {
  47547. this._updatePrimPointerPos(cur);
  47548. }
  47549. // Trigger a PointerEnter corresponding to the PointerOver
  47550. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  47551. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerEnter);
  47552. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerEnter);
  47553. }
  47554. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  47555. this._debugExecObserver(cur, BABYLON.PrimitivePointerInfo.PointerLeave);
  47556. cur._pointerEventObservable.notifyObservers(ppi, BABYLON.PrimitivePointerInfo.PointerLeave);
  47557. }
  47558. // Loop to the parent
  47559. cur = cur.parent;
  47560. }
  47561. };
  47562. Canvas2D.prototype._triggerActionManager = function (prim, ppi, mask, eventData) {
  47563. var _this = this;
  47564. // A little safe guard, it might happens than the event is triggered before the first render and nothing is computed, this simple check will make sure everything will be fine
  47565. if (!this._globalTransform) {
  47566. this.updateCachedStates(true);
  47567. }
  47568. // Process Trigger related to PointerDown
  47569. if ((mask & BABYLON.PrimitivePointerInfo.PointerDown) !== 0) {
  47570. // On pointer down, record the current position and time to be able to trick PickTrigger and LongPressTrigger
  47571. this._pickStartingPosition = ppi.primitivePointerPos.clone();
  47572. this._pickStartingTime = new Date().getTime();
  47573. this._pickedDownPrim = null;
  47574. if (prim.actionManager) {
  47575. this._pickedDownPrim = prim;
  47576. if (prim.actionManager.hasPickTriggers) {
  47577. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47578. switch (eventData.button) {
  47579. case 0:
  47580. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, actionEvent);
  47581. break;
  47582. case 1:
  47583. prim.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, actionEvent);
  47584. break;
  47585. case 2:
  47586. prim.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, actionEvent);
  47587. break;
  47588. }
  47589. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, actionEvent);
  47590. }
  47591. if (prim.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  47592. window.setTimeout(function () {
  47593. var ppi = _this._primPointerInfo;
  47594. var capturedPrim = _this.getCapturedPrimitive(ppi.pointerId);
  47595. _this._updateIntersectionList(ppi.canvasPointerPos, capturedPrim !== null);
  47596. var ii = new BABYLON.IntersectInfo2D();
  47597. ii.pickPosition = ppi.canvasPointerPos.clone();
  47598. ii.findFirstOnly = false;
  47599. _this.intersect(ii);
  47600. if (ii.isPrimIntersected(prim) !== null) {
  47601. if (prim.actionManager) {
  47602. if (_this._pickStartingTime !== 0 && ((new Date().getTime() - _this._pickStartingTime) > BABYLON.ActionManager.LongPressDelay) && (Math.abs(_this._pickStartingPosition.x - ii.pickPosition.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._pickStartingPosition.y - ii.pickPosition.y) < BABYLON.ActionManager.DragMovementThreshold)) {
  47603. _this._pickStartingTime = 0;
  47604. prim.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData));
  47605. }
  47606. }
  47607. }
  47608. }, BABYLON.ActionManager.LongPressDelay);
  47609. }
  47610. }
  47611. }
  47612. else if ((mask & BABYLON.PrimitivePointerInfo.PointerUp) !== 0) {
  47613. this._pickStartingTime = 0;
  47614. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47615. if (prim.actionManager) {
  47616. // OnPickUpTrigger
  47617. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, actionEvent);
  47618. // OnPickTrigger
  47619. if (Math.abs(this._pickStartingPosition.x - ppi.canvasPointerPos.x) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(this._pickStartingPosition.y - ppi.canvasPointerPos.y) < BABYLON.ActionManager.DragMovementThreshold) {
  47620. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, actionEvent);
  47621. }
  47622. }
  47623. // OnPickOutTrigger
  47624. if (this._pickedDownPrim && this._pickedDownPrim.actionManager && (this._pickedDownPrim !== prim)) {
  47625. this._pickedDownPrim.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, actionEvent);
  47626. }
  47627. }
  47628. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOver) !== 0) {
  47629. if (prim.actionManager) {
  47630. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47631. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, actionEvent);
  47632. }
  47633. }
  47634. else if ((mask & BABYLON.PrimitivePointerInfo.PointerOut) !== 0) {
  47635. if (prim.actionManager) {
  47636. var actionEvent = BABYLON.ActionEvent.CreateNewFromPrimitive(prim, ppi.primitivePointerPos, eventData);
  47637. prim.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, actionEvent);
  47638. }
  47639. }
  47640. };
  47641. Canvas2D.prototype._notifParents = function (prim, mask) {
  47642. var pii = this._primPointerInfo;
  47643. var curPrim = this;
  47644. while (curPrim) {
  47645. this._updatePrimPointerPos(curPrim);
  47646. // Fire the proper notification
  47647. if (mask === BABYLON.PrimitivePointerInfo.PointerOver) {
  47648. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerEnter);
  47649. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerEnter);
  47650. }
  47651. else if (mask === BABYLON.PrimitivePointerInfo.PointerOut) {
  47652. this._debugExecObserver(curPrim, BABYLON.PrimitivePointerInfo.PointerLeave);
  47653. curPrim._pointerEventObservable.notifyObservers(pii, BABYLON.PrimitivePointerInfo.PointerLeave);
  47654. }
  47655. curPrim = curPrim.parent;
  47656. }
  47657. };
  47658. /**
  47659. * Don't forget to call the dispose method when you're done with the Canvas instance.
  47660. * But don't worry, if you dispose its scene, the canvas will be automatically disposed too.
  47661. */
  47662. Canvas2D.prototype.dispose = function () {
  47663. if (!_super.prototype.dispose.call(this)) {
  47664. return false;
  47665. }
  47666. if (this._profilingCanvas) {
  47667. this._profilingCanvas.dispose();
  47668. this._profilingCanvas = null;
  47669. }
  47670. if (this.interactionEnabled) {
  47671. this._setupInteraction(false);
  47672. }
  47673. if (this._beforeRenderObserver) {
  47674. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  47675. this._beforeRenderObserver = null;
  47676. }
  47677. if (this._afterRenderObserver) {
  47678. this._scene.onAfterRenderObservable.remove(this._afterRenderObserver);
  47679. this._afterRenderObserver = null;
  47680. }
  47681. if (this._groupCacheMaps) {
  47682. this._groupCacheMaps.forEach(function (k, m) { return m.forEach(function (e) { return e.dispose(); }); });
  47683. this._groupCacheMaps = null;
  47684. }
  47685. };
  47686. Object.defineProperty(Canvas2D.prototype, "scene", {
  47687. /**
  47688. * Accessor to the Scene that owns the Canvas
  47689. * @returns The instance of the Scene object
  47690. */
  47691. get: function () {
  47692. return this._scene;
  47693. },
  47694. enumerable: true,
  47695. configurable: true
  47696. });
  47697. Object.defineProperty(Canvas2D.prototype, "engine", {
  47698. /**
  47699. * Accessor to the Engine that drives the Scene used by this Canvas
  47700. * @returns The instance of the Engine object
  47701. */
  47702. get: function () {
  47703. return this._engine;
  47704. },
  47705. enumerable: true,
  47706. configurable: true
  47707. });
  47708. Object.defineProperty(Canvas2D.prototype, "cachingStrategy", {
  47709. /**
  47710. * Accessor of the Caching Strategy used by this Canvas.
  47711. * See Canvas2D.CACHESTRATEGY_xxxx static members for more information
  47712. * @returns the value corresponding to the used strategy.
  47713. */
  47714. get: function () {
  47715. return this._cachingStrategy;
  47716. },
  47717. enumerable: true,
  47718. configurable: true
  47719. });
  47720. Object.defineProperty(Canvas2D.prototype, "isScreenSpace", {
  47721. /**
  47722. * Return true if the Canvas is a Screen Space one, false if it's a World Space one.
  47723. * @returns {}
  47724. */
  47725. get: function () {
  47726. return this._isScreenSpace;
  47727. },
  47728. enumerable: true,
  47729. configurable: true
  47730. });
  47731. Object.defineProperty(Canvas2D.prototype, "worldSpaceCanvasNode", {
  47732. /**
  47733. * Only valid for World Space Canvas, returns the scene node that displays the canvas
  47734. */
  47735. get: function () {
  47736. return this._worldSpaceNode;
  47737. },
  47738. set: function (val) {
  47739. this._worldSpaceNode = val;
  47740. },
  47741. enumerable: true,
  47742. configurable: true
  47743. });
  47744. Object.defineProperty(Canvas2D.prototype, "supportInstancedArray", {
  47745. /**
  47746. * Check if the WebGL Instanced Array extension is supported or not
  47747. */
  47748. get: function () {
  47749. return this._supprtInstancedArray;
  47750. },
  47751. enumerable: true,
  47752. configurable: true
  47753. });
  47754. Object.defineProperty(Canvas2D.prototype, "backgroundFill", {
  47755. /**
  47756. * Property that defines the fill object used to draw the background of the Canvas.
  47757. * Note that Canvas with a Caching Strategy of
  47758. * @returns If the background is not set, null will be returned, otherwise a valid fill object is returned.
  47759. */
  47760. get: function () {
  47761. if (!this._background || !this._background.isVisible) {
  47762. return null;
  47763. }
  47764. return this._background.fill;
  47765. },
  47766. set: function (value) {
  47767. this.checkBackgroundAvailability();
  47768. if (value === this._background.fill) {
  47769. return;
  47770. }
  47771. this._background.fill = value;
  47772. this._background.levelVisible = true;
  47773. },
  47774. enumerable: true,
  47775. configurable: true
  47776. });
  47777. Object.defineProperty(Canvas2D.prototype, "backgroundBorder", {
  47778. /**
  47779. * Property that defines the border object used to draw the background of the Canvas.
  47780. * @returns If the background is not set, null will be returned, otherwise a valid border object is returned.
  47781. */
  47782. get: function () {
  47783. if (!this._background || !this._background.isVisible) {
  47784. return null;
  47785. }
  47786. return this._background.border;
  47787. },
  47788. set: function (value) {
  47789. this.checkBackgroundAvailability();
  47790. if (value === this._background.border) {
  47791. return;
  47792. }
  47793. this._background.border = value;
  47794. this._background.levelVisible = true;
  47795. },
  47796. enumerable: true,
  47797. configurable: true
  47798. });
  47799. Object.defineProperty(Canvas2D.prototype, "backgroundBorderThickness", {
  47800. /**
  47801. * Property that defines the thickness of the border object used to draw the background of the Canvas.
  47802. * @returns If the background is not set, null will be returned, otherwise a valid number matching the thickness is returned.
  47803. */
  47804. get: function () {
  47805. if (!this._background || !this._background.isVisible) {
  47806. return null;
  47807. }
  47808. return this._background.borderThickness;
  47809. },
  47810. set: function (value) {
  47811. this.checkBackgroundAvailability();
  47812. if (value === this._background.borderThickness) {
  47813. return;
  47814. }
  47815. this._background.borderThickness = value;
  47816. },
  47817. enumerable: true,
  47818. configurable: true
  47819. });
  47820. Object.defineProperty(Canvas2D.prototype, "backgroundRoundRadius", {
  47821. /**
  47822. * You can set the roundRadius of the background
  47823. * @returns The current roundRadius
  47824. */
  47825. get: function () {
  47826. if (!this._background || !this._background.isVisible) {
  47827. return null;
  47828. }
  47829. return this._background.roundRadius;
  47830. },
  47831. set: function (value) {
  47832. this.checkBackgroundAvailability();
  47833. if (value === this._background.roundRadius) {
  47834. return;
  47835. }
  47836. this._background.roundRadius = value;
  47837. this._background.levelVisible = true;
  47838. },
  47839. enumerable: true,
  47840. configurable: true
  47841. });
  47842. Object.defineProperty(Canvas2D.prototype, "interactionEnabled", {
  47843. /**
  47844. * Enable/Disable interaction for this Canvas
  47845. * When enabled the Prim2DBase.pointerEventObservable property will notified when appropriate events occur
  47846. */
  47847. get: function () {
  47848. return this._interactionEnabled;
  47849. },
  47850. set: function (enable) {
  47851. this._setupInteraction(enable);
  47852. },
  47853. enumerable: true,
  47854. configurable: true
  47855. });
  47856. Object.defineProperty(Canvas2D.prototype, "_engineData", {
  47857. /**
  47858. * Access the babylon.js' engine bound data, do not invoke this method, it's for internal purpose only
  47859. * @returns {}
  47860. */
  47861. get: function () {
  47862. return this.__engineData;
  47863. },
  47864. enumerable: true,
  47865. configurable: true
  47866. });
  47867. Canvas2D.prototype.createCanvasProfileInfoCanvas = function () {
  47868. if (this._profilingCanvas) {
  47869. return this._profilingCanvas;
  47870. }
  47871. var canvas = new ScreenSpaceCanvas2D(this.scene, {
  47872. id: "ProfileInfoCanvas", cachingStrategy: Canvas2D.CACHESTRATEGY_DONTCACHE, children: [
  47873. new BABYLON.Rectangle2D({
  47874. id: "ProfileBorder", border: "#FFFFFFFF", borderThickness: 2, roundRadius: 5, fill: "#C04040C0", marginAlignment: "h: left, v: top", margin: "10", padding: "10", children: [
  47875. new BABYLON.Text2D("Stats", { id: "ProfileInfoText", marginAlignment: "h: left, v: top", fontName: "10pt Lucida Console" })
  47876. ]
  47877. })
  47878. ]
  47879. });
  47880. this._profileInfoText = canvas.findById("ProfileInfoText");
  47881. this._profilingCanvas = canvas;
  47882. return canvas;
  47883. };
  47884. Canvas2D.prototype.checkBackgroundAvailability = function () {
  47885. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS) {
  47886. throw Error("Can't use Canvas Background with the caching strategy TOPLEVELGROUPS");
  47887. }
  47888. };
  47889. Canvas2D.prototype._initPerfMetrics = function () {
  47890. this._drawCallsOpaqueCounter.fetchNewFrame();
  47891. this._drawCallsAlphaTestCounter.fetchNewFrame();
  47892. this._drawCallsTransparentCounter.fetchNewFrame();
  47893. this._groupRenderCounter.fetchNewFrame();
  47894. this._updateTransparentDataCounter.fetchNewFrame();
  47895. this._cachedGroupRenderCounter.fetchNewFrame();
  47896. this._updateCachedStateCounter.fetchNewFrame();
  47897. this._updateLayoutCounter.fetchNewFrame();
  47898. this._updatePositioningCounter.fetchNewFrame();
  47899. this._updateLocalTransformCounter.fetchNewFrame();
  47900. this._updateGlobalTransformCounter.fetchNewFrame();
  47901. this._boundingInfoRecomputeCounter.fetchNewFrame();
  47902. };
  47903. Canvas2D.prototype._fetchPerfMetrics = function () {
  47904. this._drawCallsOpaqueCounter.addCount(0, true);
  47905. this._drawCallsAlphaTestCounter.addCount(0, true);
  47906. this._drawCallsTransparentCounter.addCount(0, true);
  47907. this._groupRenderCounter.addCount(0, true);
  47908. this._updateTransparentDataCounter.addCount(0, true);
  47909. this._cachedGroupRenderCounter.addCount(0, true);
  47910. this._updateCachedStateCounter.addCount(0, true);
  47911. this._updateLayoutCounter.addCount(0, true);
  47912. this._updatePositioningCounter.addCount(0, true);
  47913. this._updateLocalTransformCounter.addCount(0, true);
  47914. this._updateGlobalTransformCounter.addCount(0, true);
  47915. this._boundingInfoRecomputeCounter.addCount(0, true);
  47916. };
  47917. Canvas2D.prototype._updateProfileCanvas = function () {
  47918. if (this._profileInfoText == null) {
  47919. return;
  47920. }
  47921. var format = function (v) { return (Math.round(v * 100) / 100).toString(); };
  47922. var p = "Draw Calls:\n" +
  47923. (" - Opaque: " + format(this.drawCallsOpaqueCounter.current) + ", (avg:" + format(this.drawCallsOpaqueCounter.lastSecAverage) + ", t:" + format(this.drawCallsOpaqueCounter.total) + ")\n") +
  47924. (" - AlphaTest: " + format(this.drawCallsAlphaTestCounter.current) + ", (avg:" + format(this.drawCallsAlphaTestCounter.lastSecAverage) + ", t:" + format(this.drawCallsAlphaTestCounter.total) + ")\n") +
  47925. (" - Transparent: " + format(this.drawCallsTransparentCounter.current) + ", (avg:" + format(this.drawCallsTransparentCounter.lastSecAverage) + ", t:" + format(this.drawCallsTransparentCounter.total) + ")\n") +
  47926. ("Group Render: " + this.groupRenderCounter.current + ", (avg:" + format(this.groupRenderCounter.lastSecAverage) + ", t:" + format(this.groupRenderCounter.total) + ")\n") +
  47927. ("Update Transparent Data: " + this.updateTransparentDataCounter.current + ", (avg:" + format(this.updateTransparentDataCounter.lastSecAverage) + ", t:" + format(this.updateTransparentDataCounter.total) + ")\n") +
  47928. ("Cached Group Render: " + this.cachedGroupRenderCounter.current + ", (avg:" + format(this.cachedGroupRenderCounter.lastSecAverage) + ", t:" + format(this.cachedGroupRenderCounter.total) + ")\n") +
  47929. ("Update Cached States: " + this.updateCachedStateCounter.current + ", (avg:" + format(this.updateCachedStateCounter.lastSecAverage) + ", t:" + format(this.updateCachedStateCounter.total) + ")\n") +
  47930. (" - Update Layout: " + this.updateLayoutCounter.current + ", (avg:" + format(this.updateLayoutCounter.lastSecAverage) + ", t:" + format(this.updateLayoutCounter.total) + ")\n") +
  47931. (" - Update Positioning: " + this.updatePositioningCounter.current + ", (avg:" + format(this.updatePositioningCounter.lastSecAverage) + ", t:" + format(this.updatePositioningCounter.total) + ")\n") +
  47932. (" - Update Local Trans: " + this.updateLocalTransformCounter.current + ", (avg:" + format(this.updateLocalTransformCounter.lastSecAverage) + ", t:" + format(this.updateLocalTransformCounter.total) + ")\n") +
  47933. (" - Update Global Trans: " + this.updateGlobalTransformCounter.current + ", (avg:" + format(this.updateGlobalTransformCounter.lastSecAverage) + ", t:" + format(this.updateGlobalTransformCounter.total) + ")\n") +
  47934. (" - BoundingInfo Recompute: " + this.boundingInfoRecomputeCounter.current + ", (avg:" + format(this.boundingInfoRecomputeCounter.lastSecAverage) + ", t:" + format(this.boundingInfoRecomputeCounter.total) + ")\n");
  47935. this._profileInfoText.text = p;
  47936. };
  47937. Canvas2D.prototype._addDrawCallCount = function (count, renderMode) {
  47938. switch (renderMode) {
  47939. case BABYLON.Render2DContext.RenderModeOpaque:
  47940. this._drawCallsOpaqueCounter.addCount(count, false);
  47941. return;
  47942. case BABYLON.Render2DContext.RenderModeAlphaTest:
  47943. this._drawCallsAlphaTestCounter.addCount(count, false);
  47944. return;
  47945. case BABYLON.Render2DContext.RenderModeTransparent:
  47946. this._drawCallsTransparentCounter.addCount(count, false);
  47947. return;
  47948. }
  47949. };
  47950. Canvas2D.prototype._addGroupRenderCount = function (count) {
  47951. this._groupRenderCounter.addCount(count, false);
  47952. };
  47953. Canvas2D.prototype._addUpdateTransparentDataCount = function (count) {
  47954. this._updateTransparentDataCounter.addCount(count, false);
  47955. };
  47956. Canvas2D.prototype.addCachedGroupRenderCounter = function (count) {
  47957. this._cachedGroupRenderCounter.addCount(count, false);
  47958. };
  47959. Canvas2D.prototype.addUpdateCachedStateCounter = function (count) {
  47960. this._updateCachedStateCounter.addCount(count, false);
  47961. };
  47962. Canvas2D.prototype.addUpdateLayoutCounter = function (count) {
  47963. this._updateLayoutCounter.addCount(count, false);
  47964. };
  47965. Canvas2D.prototype.addUpdatePositioningCounter = function (count) {
  47966. this._updatePositioningCounter.addCount(count, false);
  47967. };
  47968. Canvas2D.prototype.addupdateLocalTransformCounter = function (count) {
  47969. this._updateLocalTransformCounter.addCount(count, false);
  47970. };
  47971. Canvas2D.prototype.addUpdateGlobalTransformCounter = function (count) {
  47972. this._updateGlobalTransformCounter.addCount(count, false);
  47973. };
  47974. Canvas2D.prototype._updateTrackedNodes = function () {
  47975. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  47976. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  47977. var rh = this.engine.getRenderHeight();
  47978. var v = cam.viewport.toGlobal(this.engine.getRenderWidth(), rh);
  47979. for (var _i = 0, _a = this._trackedGroups; _i < _a.length; _i++) {
  47980. var group = _a[_i];
  47981. if (group.isDisposed || !group.isVisible) {
  47982. continue;
  47983. }
  47984. var node = group.trackedNode;
  47985. var worldMtx = node.getWorldMatrix();
  47986. var proj = BABYLON.Vector3.Project(Canvas2D._v, worldMtx, Canvas2D._m, v);
  47987. group.x = Math.round(proj.x);
  47988. group.y = Math.round(rh - proj.y);
  47989. }
  47990. };
  47991. /**
  47992. * Call this method change you want to have layout related data computed and up to date (layout area, primitive area, local/global transformation matrices)
  47993. */
  47994. Canvas2D.prototype.updateCanvasLayout = function (forceRecompute) {
  47995. this._updateCanvasState(forceRecompute);
  47996. };
  47997. Canvas2D.prototype._updateAdaptiveSizeWorldCanvas = function () {
  47998. if (this._globalTransformStep < 2) {
  47999. return;
  48000. }
  48001. var n = this.worldSpaceCanvasNode;
  48002. var bi = n.getBoundingInfo().boundingBox;
  48003. var v = bi.vectorsWorld;
  48004. var cam = this.scene.cameraToUseForPointers || this.scene.activeCamera;
  48005. cam.getViewMatrix().multiplyToRef(cam.getProjectionMatrix(), Canvas2D._m);
  48006. var vp = cam.viewport.toGlobal(this.engine.getRenderWidth(), this.engine.getRenderHeight());
  48007. var projPoints = new Array(4);
  48008. for (var i = 0; i < 4; i++) {
  48009. projPoints[i] = BABYLON.Vector3.Project(v[i], Canvas2D._mI, Canvas2D._m, vp);
  48010. }
  48011. var left = projPoints[3].subtract(projPoints[0]).length();
  48012. var top = projPoints[3].subtract(projPoints[1]).length();
  48013. var right = projPoints[1].subtract(projPoints[2]).length();
  48014. var bottom = projPoints[2].subtract(projPoints[0]).length();
  48015. var w = Math.round(Math.max(top, bottom));
  48016. var h = Math.round(Math.max(right, left));
  48017. var isW = w > h;
  48018. // Basically if it's under 256 we use 256, otherwise we take the biggest power of 2
  48019. var edge = Math.max(w, h);
  48020. if (edge < 256) {
  48021. edge = 256;
  48022. }
  48023. else {
  48024. edge = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  48025. }
  48026. // Clip values if needed
  48027. edge = Math.min(edge, this._maxAdaptiveWorldSpaceCanvasSize);
  48028. var newScale = edge / ((isW) ? this.size.width : this.size.height);
  48029. if (newScale !== this.scale) {
  48030. var scale = newScale;
  48031. // console.log(`New adaptive scale for Canvas ${this.id}, w: ${w}, h: ${h}, scale: ${scale}, edge: ${edge}, isW: ${isW}`);
  48032. this._setRenderingScale(scale);
  48033. }
  48034. };
  48035. Canvas2D.prototype._updateCanvasState = function (forceRecompute) {
  48036. // Check if the update has already been made for this render Frame
  48037. if (!forceRecompute && this.scene.getRenderId() === this._updateRenderId) {
  48038. return;
  48039. }
  48040. // Detect a change of rendering size
  48041. var renderingSizeChanged = false;
  48042. var newWidth = this.engine.getRenderWidth();
  48043. if (newWidth !== this._renderingSize.width) {
  48044. renderingSizeChanged = true;
  48045. }
  48046. this._renderingSize.width = newWidth;
  48047. var newHeight = this.engine.getRenderHeight();
  48048. if (newHeight !== this._renderingSize.height) {
  48049. renderingSizeChanged = true;
  48050. }
  48051. this._renderingSize.height = newHeight;
  48052. // If the canvas fit the rendering size and it changed, update
  48053. if (renderingSizeChanged && this._fitRenderingDevice) {
  48054. this.size = this._renderingSize;
  48055. if (this._background) {
  48056. this._background.size = this.size;
  48057. }
  48058. // Dirty the Layout at the Canvas level to recompute as the size changed
  48059. this._setLayoutDirty();
  48060. }
  48061. var context = new BABYLON.PrepareRender2DContext();
  48062. ++this._globalTransformProcessStep;
  48063. this.updateCachedStates(false);
  48064. this._prepareGroupRender(context);
  48065. this._updateRenderId = this.scene.getRenderId();
  48066. };
  48067. /**
  48068. * Method that renders the Canvas, you should not invoke
  48069. */
  48070. Canvas2D.prototype._render = function () {
  48071. this._initPerfMetrics();
  48072. this._updateTrackedNodes();
  48073. this._updateCanvasState(false);
  48074. if (!this._isScreenSpace) {
  48075. this._updateAdaptiveSizeWorldCanvas();
  48076. }
  48077. this._updateCanvasState(false);
  48078. if (this._primPointerInfo.canvasPointerPos) {
  48079. this._updateIntersectionList(this._primPointerInfo.canvasPointerPos, false);
  48080. this._updateOverStatus(); // TODO this._primPointerInfo may not be up to date!
  48081. }
  48082. this.engine.setState(false);
  48083. this._groupRender();
  48084. if (!this._isScreenSpace) {
  48085. if (this._isFlagSet(BABYLON.SmartPropertyPrim.flagWorldCacheChanged)) {
  48086. this.worldSpaceCacheChanged();
  48087. this._clearFlags(BABYLON.SmartPropertyPrim.flagWorldCacheChanged);
  48088. }
  48089. }
  48090. // If the canvas is cached at canvas level, we must manually render the sprite that will display its content
  48091. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS && this._cachedCanvasGroup) {
  48092. this._cachedCanvasGroup._renderCachedCanvas();
  48093. }
  48094. this._fetchPerfMetrics();
  48095. this._updateProfileCanvas();
  48096. };
  48097. /**
  48098. * Internal method that allocate a cache for the given group.
  48099. * Caching is made using a collection of MapTexture where many groups have their bitmap cache stored inside.
  48100. * @param group The group to allocate the cache of.
  48101. * @return custom type with the PackedRect instance giving information about the cache location into the texture and also the MapTexture instance that stores the cache.
  48102. */
  48103. Canvas2D.prototype._allocateGroupCache = function (group, parent, minSize, useMipMap, anisotropicLevel) {
  48104. if (useMipMap === void 0) { useMipMap = false; }
  48105. if (anisotropicLevel === void 0) { anisotropicLevel = 1; }
  48106. var key = (useMipMap ? "MipMap" : "NoMipMap") + "_" + anisotropicLevel;
  48107. // Determine size
  48108. var size = group.actualSize;
  48109. size = new BABYLON.Size(Math.ceil(size.width), Math.ceil(size.height));
  48110. if (minSize) {
  48111. size.width = Math.max(minSize.width, size.width);
  48112. size.height = Math.max(minSize.height, size.height);
  48113. }
  48114. var mapArray = this._groupCacheMaps.getOrAddWithFactory(key, function () { return new Array(); });
  48115. // Try to find a spot in one of the cached texture
  48116. var res = null;
  48117. var map;
  48118. for (var _i = 0, mapArray_1 = mapArray; _i < mapArray_1.length; _i++) {
  48119. var _map = mapArray_1[_i];
  48120. map = _map;
  48121. var node = map.allocateRect(size);
  48122. if (node) {
  48123. res = { node: node, texture: map };
  48124. break;
  48125. }
  48126. }
  48127. // Couldn't find a map that could fit the rect, create a new map for it
  48128. if (!res) {
  48129. var mapSize = new BABYLON.Size(Canvas2D._groupTextureCacheSize, Canvas2D._groupTextureCacheSize);
  48130. // Check if the predefined size would fit, other create a custom size using the nearest bigger power of 2
  48131. if (size.width > mapSize.width || size.height > mapSize.height) {
  48132. mapSize.width = Math.pow(2, Math.ceil(Math.log(size.width) / Math.log(2)));
  48133. mapSize.height = Math.pow(2, Math.ceil(Math.log(size.height) / Math.log(2)));
  48134. }
  48135. var id = "groupsMapChache" + this._mapCounter++ + "forCanvas" + this.id;
  48136. map = new BABYLON.MapTexture(id, this._scene, mapSize, useMipMap ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : BABYLON.Texture.BILINEAR_SAMPLINGMODE, useMipMap);
  48137. map.hasAlpha = true;
  48138. map.anisotropicFilteringLevel = 4;
  48139. mapArray.splice(0, 0, map);
  48140. var node = map.allocateRect(size);
  48141. res = { node: node, texture: map };
  48142. }
  48143. // Check if we have to create a Sprite that will display the content of the Canvas which is cached.
  48144. // Don't do it in case of the group being a worldspace canvas (because its texture is bound to a WorldSpaceCanvas node)
  48145. if (group !== this || this._isScreenSpace) {
  48146. var node = res.node;
  48147. // Special case if the canvas is entirely cached: create a group that will have a single sprite it will be rendered specifically at the very end of the rendering process
  48148. if (this._cachingStrategy === Canvas2D.CACHESTRATEGY_CANVAS) {
  48149. this._cachedCanvasGroup = BABYLON.Group2D._createCachedCanvasGroup(this);
  48150. var sprite = new BABYLON.Sprite2D(map, { parent: this._cachedCanvasGroup, id: "__cachedCanvasSprite__", spriteSize: node.contentSize, spriteLocation: node.pos });
  48151. sprite.zOrder = 1;
  48152. sprite.origin = BABYLON.Vector2.Zero();
  48153. }
  48154. else {
  48155. var sprite = new BABYLON.Sprite2D(map, { parent: parent, id: "__cachedSpriteOfGroup__" + group.id, x: group.actualPosition.x, y: group.actualPosition.y, spriteSize: node.contentSize, spriteLocation: node.pos });
  48156. sprite.origin = group.origin.clone();
  48157. sprite.addExternalData("__cachedGroup__", group);
  48158. sprite.pointerEventObservable.add(function (e, s) {
  48159. if (group.pointerEventObservable !== null) {
  48160. group.pointerEventObservable.notifyObservers(e, s.mask);
  48161. }
  48162. });
  48163. res.sprite = sprite;
  48164. }
  48165. }
  48166. return res;
  48167. };
  48168. /**
  48169. * Internal method used to register a Scene Node to track position for the given group
  48170. * Do not invoke this method, for internal purpose only.
  48171. * @param group the group to track its associated Scene Node
  48172. */
  48173. Canvas2D.prototype._registerTrackedNode = function (group) {
  48174. if (group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  48175. return;
  48176. }
  48177. this._trackedGroups.push(group);
  48178. group._setFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  48179. };
  48180. /**
  48181. * Internal method used to unregister a tracked Scene Node
  48182. * Do not invoke this method, it's for internal purpose only.
  48183. * @param group the group to unregister its tracked Scene Node from.
  48184. */
  48185. Canvas2D.prototype._unregisterTrackedNode = function (group) {
  48186. if (!group._isFlagSet(BABYLON.SmartPropertyPrim.flagTrackedGroup)) {
  48187. return;
  48188. }
  48189. var i = this._trackedGroups.indexOf(group);
  48190. if (i !== -1) {
  48191. this._trackedGroups.splice(i, 1);
  48192. }
  48193. group._clearFlags(BABYLON.SmartPropertyPrim.flagTrackedGroup);
  48194. };
  48195. /**
  48196. * Get a Solid Color Brush instance matching the given color.
  48197. * @param color The color to retrieve
  48198. * @return A shared instance of the SolidColorBrush2D class that use the given color
  48199. */
  48200. Canvas2D.GetSolidColorBrush = function (color) {
  48201. return Canvas2D._solidColorBrushes.getOrAddWithFactory(color.toHexString(), function () { return new BABYLON.SolidColorBrush2D(color.clone(), true); });
  48202. };
  48203. /**
  48204. * Get a Solid Color Brush instance matching the given color expressed as a CSS formatted hexadecimal value.
  48205. * @param color The color to retrieve
  48206. * @return A shared instance of the SolidColorBrush2D class that uses the given color
  48207. */
  48208. Canvas2D.GetSolidColorBrushFromHex = function (hexValue) {
  48209. return Canvas2D._solidColorBrushes.getOrAddWithFactory(hexValue, function () { return new BABYLON.SolidColorBrush2D(BABYLON.Color4.FromHexString(hexValue), true); });
  48210. };
  48211. /**
  48212. * Get a Gradient Color Brush
  48213. * @param color1 starting color
  48214. * @param color2 engine color
  48215. * @param translation translation vector to apply. default is [0;0]
  48216. * @param rotation rotation in radian to apply to the brush, initial direction is top to bottom. rotation is counter clockwise. default is 0.
  48217. * @param scale scaling factor to apply. default is 1.
  48218. */
  48219. Canvas2D.GetGradientColorBrush = function (color1, color2, translation, rotation, scale) {
  48220. if (translation === void 0) { translation = BABYLON.Vector2.Zero(); }
  48221. if (rotation === void 0) { rotation = 0; }
  48222. if (scale === void 0) { scale = 1; }
  48223. return Canvas2D._gradientColorBrushes.getOrAddWithFactory(BABYLON.GradientColorBrush2D.BuildKey(color1, color2, translation, rotation, scale), function () { return new BABYLON.GradientColorBrush2D(color1, color2, translation, rotation, scale, true); });
  48224. };
  48225. /**
  48226. * Create a solid or gradient brush from a string value.
  48227. * @param brushString should be either
  48228. * - "solid: #RRGGBBAA" or "#RRGGBBAA"
  48229. * - "gradient: #FF808080, #FFFFFFF[, [10:20], 180, 1]" for color1, color2, translation, rotation (degree), scale. The last three are optionals, but if specified must be is this order. "gradient:" can be omitted.
  48230. */
  48231. Canvas2D.GetBrushFromString = function (brushString) {
  48232. // Note: yes, I hate/don't know RegEx.. Feel free to add your contribution to the cause!
  48233. brushString = brushString.trim();
  48234. var split = brushString.split(",");
  48235. // Solid, formatted as: "[solid:]#FF808080"
  48236. if (split.length === 1) {
  48237. var value = null;
  48238. if (brushString.indexOf("solid:") === 0) {
  48239. value = brushString.substr(6).trim();
  48240. }
  48241. else if (brushString.indexOf("#") === 0) {
  48242. value = brushString;
  48243. }
  48244. else {
  48245. return null;
  48246. }
  48247. return Canvas2D.GetSolidColorBrushFromHex(value);
  48248. }
  48249. else {
  48250. if (split[0].indexOf("gradient:") === 0) {
  48251. split[0] = split[0].substr(9).trim();
  48252. }
  48253. try {
  48254. var start = BABYLON.Color4.FromHexString(split[0].trim());
  48255. var end = BABYLON.Color4.FromHexString(split[1].trim());
  48256. var t = BABYLON.Vector2.Zero();
  48257. if (split.length > 2) {
  48258. var v = split[2].trim();
  48259. if (v.charAt(0) !== "[" || v.charAt(v.length - 1) !== "]") {
  48260. return null;
  48261. }
  48262. var sep = v.indexOf(":");
  48263. var x = parseFloat(v.substr(1, sep));
  48264. var y = parseFloat(v.substr(sep + 1, v.length - (sep + 1)));
  48265. t = new BABYLON.Vector2(x, y);
  48266. }
  48267. var r = 0;
  48268. if (split.length > 3) {
  48269. r = BABYLON.Tools.ToRadians(parseFloat(split[3].trim()));
  48270. }
  48271. var s = 1;
  48272. if (split.length > 4) {
  48273. s = parseFloat(split[4].trim());
  48274. }
  48275. return Canvas2D.GetGradientColorBrush(start, end, t, r, s);
  48276. }
  48277. catch (e) {
  48278. return null;
  48279. }
  48280. }
  48281. };
  48282. /**
  48283. * In this strategy only the direct children groups of the Canvas will be cached, their whole content (whatever the sub groups they have) into a single bitmap.
  48284. * This strategy doesn't allow primitives added directly as children of the Canvas.
  48285. * You typically want to use this strategy of a screenSpace fullscreen canvas: you don't want a bitmap cache taking the whole screen resolution but still want the main contents (say UI in the topLeft and rightBottom for instance) to be efficiently cached.
  48286. */
  48287. Canvas2D.CACHESTRATEGY_TOPLEVELGROUPS = 1;
  48288. /**
  48289. * In this strategy each group will have its own cache bitmap (except if a given group explicitly defines the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors).
  48290. * This strategy is typically used if the canvas has some groups that are frequently animated. Unchanged ones will have a steady cache and the others will be refreshed when they change, reducing the redraw operation count to their content only.
  48291. * When using this strategy, group instances can rely on the DONTCACHEOVERRIDE or CACHEINPARENTGROUP behaviors to minimize the amount of cached bitmaps.
  48292. * Note that in this mode the Canvas itself is not cached, it only contains the sprites of its direct children group to render, there's no point to cache the whole canvas, sprites will be rendered pretty efficiently, the memory cost would be too great for the value of it.
  48293. */
  48294. Canvas2D.CACHESTRATEGY_ALLGROUPS = 2;
  48295. /**
  48296. * In this strategy the whole canvas is cached into a single bitmap containing every primitives it owns, at the exception of the ones that are owned by a group having the DONTCACHEOVERRIDE behavior (these primitives will be directly drawn to the viewport at each render for screenSpace Canvas or be part of the Canvas cache bitmap for worldSpace Canvas).
  48297. */
  48298. Canvas2D.CACHESTRATEGY_CANVAS = 3;
  48299. /**
  48300. * This strategy is used to recompose/redraw the canvas entirely at each viewport render.
  48301. * Use this strategy if memory is a concern above rendering performances and/or if the canvas is frequently animated (hence reducing the benefits of caching).
  48302. * Note that you can't use this strategy for WorldSpace Canvas, they need at least a top level group caching.
  48303. */
  48304. Canvas2D.CACHESTRATEGY_DONTCACHE = 4;
  48305. Canvas2D._zMinDelta = 1 / (Math.pow(2, 24) - 1);
  48306. Canvas2D._interInfo = new BABYLON.IntersectInfo2D();
  48307. Canvas2D._v = BABYLON.Vector3.Zero(); // Must stay zero
  48308. Canvas2D._m = BABYLON.Matrix.Identity();
  48309. Canvas2D._mI = BABYLON.Matrix.Identity(); // Must stay identity
  48310. /**
  48311. * Define the default size used for both the width and height of a MapTexture to allocate.
  48312. * Note that some MapTexture might be bigger than this size if the first node to allocate is bigger in width or height
  48313. */
  48314. Canvas2D._groupTextureCacheSize = 1024;
  48315. Canvas2D._solidColorBrushes = new BABYLON.StringDictionary();
  48316. Canvas2D._gradientColorBrushes = new BABYLON.StringDictionary();
  48317. Canvas2D = __decorate([
  48318. BABYLON.className("Canvas2D")
  48319. ], Canvas2D);
  48320. return Canvas2D;
  48321. }(BABYLON.Group2D));
  48322. BABYLON.Canvas2D = Canvas2D;
  48323. var WorldSpaceCanvas2D = (function (_super) {
  48324. __extends(WorldSpaceCanvas2D, _super);
  48325. /**
  48326. * Create a new 2D WorldSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a world transformation information to place it in the world space.
  48327. * This kind of canvas can't have its Primitives directly drawn in the Viewport, they need to be cached in a bitmap at some point, as a consequence the DONT_CACHE strategy is unavailable. For now only CACHESTRATEGY_CANVAS is supported, but the remaining strategies will be soon.
  48328. * @param scene the Scene that owns the Canvas
  48329. * @param size the dimension of the Canvas in World Space
  48330. * @param settings a combination of settings, possible ones are
  48331. * - children: an array of direct children primitives
  48332. * - id: a text identifier, for information purpose only, default is null.
  48333. * - worldPosition the position of the Canvas in World Space, default is [0,0,0]
  48334. * - worldRotation the rotation of the Canvas in World Space, default is Quaternion.Identity()
  48335. * - sideOrientation: Unexpected behavior occur if the value is different from Mesh.DEFAULTSIDE right now, so please use this one, which is the default.
  48336. * - cachingStrategy Must be CACHESTRATEGY_CANVAS for now, which is the default.
  48337. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is false (the opposite of ScreenSpace).
  48338. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  48339. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  48340. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  48341. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see Canvas2D.GetBrushFromString) or a IBrush2D instance.
  48342. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  48343. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  48344. * - maxAdaptiveCanvasSize: set the max size (width and height) of the bitmap that will contain the cached version of the WorldSpace Canvas. Default is 1024 or less if it's not supported. In any case the value you give will be clipped by the maximum that WebGL supports on the running device. You can set any size, more than 1024 if you want, but testing proved it's a good max value for non "retina" like screens.
  48345. * - paddingTop: top padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48346. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48347. * - paddingRight: right padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48348. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see PrimitiveThickness.fromString)
  48349. * - padding: top, left, right and bottom padding formatted as a single string (see PrimitiveThickness.fromString)
  48350. */
  48351. function WorldSpaceCanvas2D(scene, size, settings) {
  48352. BABYLON.Prim2DBase._isCanvasInit = true;
  48353. var s = settings;
  48354. s.isScreenSpace = false;
  48355. s.size = size.clone();
  48356. settings.cachingStrategy = (settings.cachingStrategy == null) ? Canvas2D.CACHESTRATEGY_CANVAS : settings.cachingStrategy;
  48357. if (settings.cachingStrategy !== Canvas2D.CACHESTRATEGY_CANVAS) {
  48358. throw new Error("Right now only the CACHESTRATEGY_CANVAS cache Strategy is supported for WorldSpace Canvas. More will come soon!");
  48359. }
  48360. _super.call(this, scene, settings);
  48361. BABYLON.Prim2DBase._isCanvasInit = false;
  48362. this._renderableData._useMipMap = true;
  48363. this._renderableData._anisotropicLevel = 8;
  48364. //if (cachingStrategy === Canvas2D.CACHESTRATEGY_DONTCACHE) {
  48365. // throw new Error("CACHESTRATEGY_DONTCACHE cache Strategy can't be used for WorldSpace Canvas");
  48366. //}
  48367. var createWorldSpaceNode = !settings || (settings.customWorldSpaceNode == null);
  48368. var id = settings ? settings.id || null : null;
  48369. // Set the max size of texture allowed for the adaptive render of the world space canvas cached bitmap
  48370. var capMaxTextSize = this.engine.getCaps().maxRenderTextureSize;
  48371. var defaultTextSize = (Math.min(capMaxTextSize, 1024)); // Default is 4K if allowed otherwise the max allowed
  48372. if (settings.maxAdaptiveCanvasSize == null) {
  48373. this._maxAdaptiveWorldSpaceCanvasSize = defaultTextSize;
  48374. }
  48375. else {
  48376. // We still clip the given value with the max allowed, the user may not be aware of these limitations
  48377. this._maxAdaptiveWorldSpaceCanvasSize = Math.min(settings.maxAdaptiveCanvasSize, capMaxTextSize);
  48378. }
  48379. if (createWorldSpaceNode) {
  48380. var plane = new BABYLON.WorldSpaceCanvas2DNode(id, scene, this);
  48381. var vertexData = BABYLON.VertexData.CreatePlane({
  48382. width: size.width,
  48383. height: size.height,
  48384. sideOrientation: settings && settings.sideOrientation || BABYLON.Mesh.DEFAULTSIDE
  48385. });
  48386. var mtl = new BABYLON.StandardMaterial(id + "_Material", scene);
  48387. this.applyCachedTexture(vertexData, mtl);
  48388. vertexData.applyToMesh(plane, true);
  48389. mtl.specularColor = new BABYLON.Color3(0, 0, 0);
  48390. mtl.disableLighting = true;
  48391. mtl.useAlphaFromDiffuseTexture = true;
  48392. plane.position = settings && settings.worldPosition || BABYLON.Vector3.Zero();
  48393. plane.rotationQuaternion = settings && settings.worldRotation || BABYLON.Quaternion.Identity();
  48394. plane.material = mtl;
  48395. this._worldSpaceNode = plane;
  48396. }
  48397. else {
  48398. this._worldSpaceNode = settings.customWorldSpaceNode;
  48399. this.applyCachedTexture(null, null);
  48400. }
  48401. }
  48402. WorldSpaceCanvas2D = __decorate([
  48403. BABYLON.className("WorldSpaceCanvas2D")
  48404. ], WorldSpaceCanvas2D);
  48405. return WorldSpaceCanvas2D;
  48406. }(Canvas2D));
  48407. BABYLON.WorldSpaceCanvas2D = WorldSpaceCanvas2D;
  48408. var ScreenSpaceCanvas2D = (function (_super) {
  48409. __extends(ScreenSpaceCanvas2D, _super);
  48410. /**
  48411. * Create a new 2D ScreenSpace Rendering Canvas, it is a 2D rectangle that has a size (width/height) and a position relative to the bottom/left corner of the screen.
  48412. * ScreenSpace Canvas will be drawn in the Viewport as a 2D Layer lying to the top of the 3D Scene. Typically used for traditional UI.
  48413. * All caching strategies will be available.
  48414. * PLEASE NOTE: the origin of a Screen Space Canvas is set to [0;0] (bottom/left) which is different than the default origin of a Primitive which is centered [0.5;0.5]
  48415. * @param scene the Scene that owns the Canvas
  48416. * @param settings a combination of settings, possible ones are
  48417. * - children: an array of direct children primitives
  48418. * - id: a text identifier, for information purpose only
  48419. * - x: the position along the x axis (horizontal), relative to the left edge of the viewport. you can alternatively use the position setting.
  48420. * - y: the position along the y axis (vertically), relative to the bottom edge of the viewport. you can alternatively use the position setting.
  48421. * - position: the position of the canvas, relative from the bottom/left of the scene's viewport. Alternatively you can set the x and y properties directly. Default value is [0, 0]
  48422. * - width: the width of the Canvas. you can alternatively use the size setting.
  48423. * - height: the height of the Canvas. you can alternatively use the size setting.
  48424. * - size: the Size of the canvas. Alternatively the width and height properties can be set. If null two behaviors depend on the cachingStrategy: if it's CACHESTRATEGY_CACHECANVAS then it will always auto-fit the rendering device, in all the other modes it will fit the content of the Canvas
  48425. * - cachingStrategy: either CACHESTRATEGY_TOPLEVELGROUPS, CACHESTRATEGY_ALLGROUPS, CACHESTRATEGY_CANVAS, CACHESTRATEGY_DONTCACHE. Please refer to their respective documentation for more information. Default is Canvas2D.CACHESTRATEGY_DONTCACHE
  48426. * - enableInteraction: if true the pointer events will be listened and rerouted to the appropriate primitives of the Canvas2D through the Prim2DBase.onPointerEventObservable observable property. Default is true.
  48427. * - isVisible: true if the canvas must be visible, false for hidden. Default is true.
  48428. * - backgroundRoundRadius: the round radius of the background, either backgroundFill or backgroundBorder must be specified.
  48429. * - backgroundFill: the brush to use to create a background fill for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  48430. * - backgroundBorder: the brush to use to create a background border for the canvas. can be a string value (see BABYLON.Canvas2D.GetBrushFromString) or a IBrush2D instance.
  48431. * - backgroundBorderThickness: if a backgroundBorder is specified, its thickness can be set using this property
  48432. * - customWorldSpaceNode: if specified the Canvas will be rendered in this given Node. But it's the responsibility of the caller to set the "worldSpaceToNodeLocal" property to compute the hit of the mouse ray into the node (in world coordinate system) as well as rendering the cached bitmap in the node itself. The properties cachedRect and cachedTexture of Group2D will give you what you need to do that.
  48433. * - paddingTop: top padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48434. * - paddingLeft: left padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48435. * - paddingRight: right padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48436. * - paddingBottom: bottom padding, can be a number (will be pixels) or a string (see BABYLON.PrimitiveThickness.fromString)
  48437. * - padding: top, left, right and bottom padding formatted as a single string (see BABYLON.PrimitiveThickness.fromString)
  48438. */
  48439. function ScreenSpaceCanvas2D(scene, settings) {
  48440. BABYLON.Prim2DBase._isCanvasInit = true;
  48441. _super.call(this, scene, settings);
  48442. }
  48443. ScreenSpaceCanvas2D = __decorate([
  48444. BABYLON.className("ScreenSpaceCanvas2D")
  48445. ], ScreenSpaceCanvas2D);
  48446. return ScreenSpaceCanvas2D;
  48447. }(Canvas2D));
  48448. BABYLON.ScreenSpaceCanvas2D = ScreenSpaceCanvas2D;
  48449. })(BABYLON || (BABYLON = {}));
  48450. var BABYLON;
  48451. (function (BABYLON) {
  48452. /**
  48453. * This is the class that is used to display a World Space Canvas into a 3D scene
  48454. */
  48455. var WorldSpaceCanvas2DNode = (function (_super) {
  48456. __extends(WorldSpaceCanvas2DNode, _super);
  48457. function WorldSpaceCanvas2DNode(name, scene, canvas) {
  48458. _super.call(this, name, scene);
  48459. this._canvas = canvas;
  48460. }
  48461. WorldSpaceCanvas2DNode.prototype.dispose = function () {
  48462. _super.prototype.dispose.call(this);
  48463. if (this._canvas) {
  48464. this._canvas.dispose();
  48465. this._canvas = null;
  48466. }
  48467. };
  48468. return WorldSpaceCanvas2DNode;
  48469. }(BABYLON.Mesh));
  48470. BABYLON.WorldSpaceCanvas2DNode = WorldSpaceCanvas2DNode;
  48471. })(BABYLON || (BABYLON = {}));
  48472. var BABYLON;
  48473. (function (BABYLON) {
  48474. var LayoutEngineBase = (function () {
  48475. function LayoutEngineBase() {
  48476. this.layoutDirtyOnPropertyChangedMask = 0;
  48477. }
  48478. LayoutEngineBase.prototype.updateLayout = function (prim) {
  48479. };
  48480. Object.defineProperty(LayoutEngineBase.prototype, "isChildPositionAllowed", {
  48481. get: function () {
  48482. return false;
  48483. },
  48484. enumerable: true,
  48485. configurable: true
  48486. });
  48487. LayoutEngineBase.prototype.isLocked = function () {
  48488. return this._isLocked;
  48489. };
  48490. LayoutEngineBase.prototype.lock = function () {
  48491. if (this._isLocked) {
  48492. return false;
  48493. }
  48494. this._isLocked = true;
  48495. return true;
  48496. };
  48497. LayoutEngineBase = __decorate([
  48498. BABYLON.className("LayoutEngineBase")
  48499. ], LayoutEngineBase);
  48500. return LayoutEngineBase;
  48501. }());
  48502. BABYLON.LayoutEngineBase = LayoutEngineBase;
  48503. var CanvasLayoutEngine = (function (_super) {
  48504. __extends(CanvasLayoutEngine, _super);
  48505. function CanvasLayoutEngine() {
  48506. _super.apply(this, arguments);
  48507. }
  48508. // A very simple (no) layout computing...
  48509. // The Canvas and its direct children gets the Canvas' size as Layout Area
  48510. // Indirect children have their Layout Area to the actualSize (margin area) of their parent
  48511. CanvasLayoutEngine.prototype.updateLayout = function (prim) {
  48512. // If this prim is layoutDiry we update its layoutArea and also the one of its direct children
  48513. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  48514. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  48515. var child = _a[_i];
  48516. this._doUpdate(child);
  48517. }
  48518. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  48519. }
  48520. };
  48521. CanvasLayoutEngine.prototype._doUpdate = function (prim) {
  48522. // Canvas ?
  48523. if (prim instanceof BABYLON.Canvas2D) {
  48524. prim.layoutArea = prim.actualSize;
  48525. }
  48526. else if (prim.parent instanceof BABYLON.Canvas2D) {
  48527. prim.layoutArea = prim.owner.actualSize;
  48528. }
  48529. else {
  48530. prim.layoutArea = prim.parent.contentArea;
  48531. }
  48532. };
  48533. Object.defineProperty(CanvasLayoutEngine.prototype, "isChildPositionAllowed", {
  48534. get: function () {
  48535. return true;
  48536. },
  48537. enumerable: true,
  48538. configurable: true
  48539. });
  48540. CanvasLayoutEngine.Singleton = new CanvasLayoutEngine();
  48541. CanvasLayoutEngine = __decorate([
  48542. BABYLON.className("CanvasLayoutEngine")
  48543. ], CanvasLayoutEngine);
  48544. return CanvasLayoutEngine;
  48545. }(LayoutEngineBase));
  48546. BABYLON.CanvasLayoutEngine = CanvasLayoutEngine;
  48547. var StackPanelLayoutEngine = (function (_super) {
  48548. __extends(StackPanelLayoutEngine, _super);
  48549. function StackPanelLayoutEngine() {
  48550. _super.call(this);
  48551. this._isHorizontal = true;
  48552. this.layoutDirtyOnPropertyChangedMask = BABYLON.Prim2DBase.sizeProperty.flagId;
  48553. }
  48554. Object.defineProperty(StackPanelLayoutEngine, "Horizontal", {
  48555. get: function () {
  48556. if (!StackPanelLayoutEngine._horizontal) {
  48557. StackPanelLayoutEngine._horizontal = new StackPanelLayoutEngine();
  48558. StackPanelLayoutEngine._horizontal.isHorizontal = true;
  48559. StackPanelLayoutEngine._horizontal.lock();
  48560. }
  48561. return StackPanelLayoutEngine._horizontal;
  48562. },
  48563. enumerable: true,
  48564. configurable: true
  48565. });
  48566. Object.defineProperty(StackPanelLayoutEngine, "Vertical", {
  48567. get: function () {
  48568. if (!StackPanelLayoutEngine._vertical) {
  48569. StackPanelLayoutEngine._vertical = new StackPanelLayoutEngine();
  48570. StackPanelLayoutEngine._vertical.isHorizontal = false;
  48571. StackPanelLayoutEngine._vertical.lock();
  48572. }
  48573. return StackPanelLayoutEngine._vertical;
  48574. },
  48575. enumerable: true,
  48576. configurable: true
  48577. });
  48578. Object.defineProperty(StackPanelLayoutEngine.prototype, "isHorizontal", {
  48579. get: function () {
  48580. return this._isHorizontal;
  48581. },
  48582. set: function (val) {
  48583. if (this.isLocked()) {
  48584. return;
  48585. }
  48586. this._isHorizontal = val;
  48587. },
  48588. enumerable: true,
  48589. configurable: true
  48590. });
  48591. StackPanelLayoutEngine.prototype.updateLayout = function (prim) {
  48592. if (prim._isFlagSet(BABYLON.SmartPropertyPrim.flagLayoutDirty)) {
  48593. var x = 0;
  48594. var y = 0;
  48595. var h = this.isHorizontal;
  48596. var max = 0;
  48597. for (var _i = 0, _a = prim.children; _i < _a.length; _i++) {
  48598. var child = _a[_i];
  48599. var layoutArea = child.layoutArea;
  48600. child.margin.computeArea(child.actualSize, layoutArea);
  48601. max = Math.max(max, h ? layoutArea.height : layoutArea.width);
  48602. }
  48603. for (var _b = 0, _c = prim.children; _b < _c.length; _b++) {
  48604. var child = _c[_b];
  48605. child.layoutAreaPos = new BABYLON.Vector2(x, y);
  48606. var layoutArea = child.layoutArea;
  48607. if (h) {
  48608. x += layoutArea.width;
  48609. child.layoutArea = new BABYLON.Size(layoutArea.width, max);
  48610. }
  48611. else {
  48612. y += layoutArea.height;
  48613. child.layoutArea = new BABYLON.Size(max, layoutArea.height);
  48614. }
  48615. }
  48616. prim._clearFlags(BABYLON.SmartPropertyPrim.flagLayoutDirty);
  48617. }
  48618. };
  48619. Object.defineProperty(StackPanelLayoutEngine.prototype, "isChildPositionAllowed", {
  48620. get: function () {
  48621. return false;
  48622. },
  48623. enumerable: true,
  48624. configurable: true
  48625. });
  48626. StackPanelLayoutEngine._horizontal = null;
  48627. StackPanelLayoutEngine._vertical = null;
  48628. StackPanelLayoutEngine = __decorate([
  48629. BABYLON.className("StackPanelLayoutEngine")
  48630. ], StackPanelLayoutEngine);
  48631. return StackPanelLayoutEngine;
  48632. }(LayoutEngineBase));
  48633. BABYLON.StackPanelLayoutEngine = StackPanelLayoutEngine;
  48634. })(BABYLON || (BABYLON = {}));
  48635. var BABYLON;
  48636. (function (BABYLON) {
  48637. var ShaderMaterial = (function (_super) {
  48638. __extends(ShaderMaterial, _super);
  48639. function ShaderMaterial(name, scene, shaderPath, options) {
  48640. _super.call(this, name, scene);
  48641. this._textures = {};
  48642. this._textureArrays = {};
  48643. this._floats = {};
  48644. this._floatsArrays = {};
  48645. this._colors3 = {};
  48646. this._colors4 = {};
  48647. this._vectors2 = {};
  48648. this._vectors3 = {};
  48649. this._vectors4 = {};
  48650. this._matrices = {};
  48651. this._matrices3x3 = {};
  48652. this._matrices2x2 = {};
  48653. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  48654. this._shaderPath = shaderPath;
  48655. options.needAlphaBlending = options.needAlphaBlending || false;
  48656. options.needAlphaTesting = options.needAlphaTesting || false;
  48657. options.attributes = options.attributes || ["position", "normal", "uv"];
  48658. options.uniforms = options.uniforms || ["worldViewProjection"];
  48659. options.samplers = options.samplers || [];
  48660. options.defines = options.defines || [];
  48661. this._options = options;
  48662. }
  48663. ShaderMaterial.prototype.needAlphaBlending = function () {
  48664. return this._options.needAlphaBlending;
  48665. };
  48666. ShaderMaterial.prototype.needAlphaTesting = function () {
  48667. return this._options.needAlphaTesting;
  48668. };
  48669. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  48670. if (this._options.uniforms.indexOf(uniformName) === -1) {
  48671. this._options.uniforms.push(uniformName);
  48672. }
  48673. };
  48674. ShaderMaterial.prototype.setTexture = function (name, texture) {
  48675. if (this._options.samplers.indexOf(name) === -1) {
  48676. this._options.samplers.push(name);
  48677. }
  48678. this._textures[name] = texture;
  48679. return this;
  48680. };
  48681. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  48682. if (this._options.samplers.indexOf(name) === -1) {
  48683. this._options.samplers.push(name);
  48684. }
  48685. this._checkUniform(name);
  48686. this._textureArrays[name] = textures;
  48687. return this;
  48688. };
  48689. ShaderMaterial.prototype.setFloat = function (name, value) {
  48690. this._checkUniform(name);
  48691. this._floats[name] = value;
  48692. return this;
  48693. };
  48694. ShaderMaterial.prototype.setFloats = function (name, value) {
  48695. this._checkUniform(name);
  48696. this._floatsArrays[name] = value;
  48697. return this;
  48698. };
  48699. ShaderMaterial.prototype.setColor3 = function (name, value) {
  48700. this._checkUniform(name);
  48701. this._colors3[name] = value;
  48702. return this;
  48703. };
  48704. ShaderMaterial.prototype.setColor4 = function (name, value) {
  48705. this._checkUniform(name);
  48706. this._colors4[name] = value;
  48707. return this;
  48708. };
  48709. ShaderMaterial.prototype.setVector2 = function (name, value) {
  48710. this._checkUniform(name);
  48711. this._vectors2[name] = value;
  48712. return this;
  48713. };
  48714. ShaderMaterial.prototype.setVector3 = function (name, value) {
  48715. this._checkUniform(name);
  48716. this._vectors3[name] = value;
  48717. return this;
  48718. };
  48719. ShaderMaterial.prototype.setVector4 = function (name, value) {
  48720. this._checkUniform(name);
  48721. this._vectors4[name] = value;
  48722. return this;
  48723. };
  48724. ShaderMaterial.prototype.setMatrix = function (name, value) {
  48725. this._checkUniform(name);
  48726. this._matrices[name] = value;
  48727. return this;
  48728. };
  48729. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  48730. this._checkUniform(name);
  48731. this._matrices3x3[name] = value;
  48732. return this;
  48733. };
  48734. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  48735. this._checkUniform(name);
  48736. this._matrices2x2[name] = value;
  48737. return this;
  48738. };
  48739. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  48740. var scene = this.getScene();
  48741. var engine = scene.getEngine();
  48742. if (!this.checkReadyOnEveryCall) {
  48743. if (this._renderId === scene.getRenderId()) {
  48744. return true;
  48745. }
  48746. }
  48747. // Instances
  48748. var defines = [];
  48749. var fallbacks = new BABYLON.EffectFallbacks();
  48750. if (useInstances) {
  48751. defines.push("#define INSTANCES");
  48752. }
  48753. for (var index = 0; index < this._options.defines.length; index++) {
  48754. defines.push(this._options.defines[index]);
  48755. }
  48756. // Bones
  48757. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  48758. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48759. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48760. fallbacks.addCPUSkinningFallback(0, mesh);
  48761. }
  48762. // Alpha test
  48763. if (engine.getAlphaTesting()) {
  48764. defines.push("#define ALPHATEST");
  48765. }
  48766. var previousEffect = this._effect;
  48767. var join = defines.join("\n");
  48768. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  48769. if (!this._effect.isReady()) {
  48770. return false;
  48771. }
  48772. if (previousEffect !== this._effect) {
  48773. scene.resetCachedMaterial();
  48774. }
  48775. this._renderId = scene.getRenderId();
  48776. return true;
  48777. };
  48778. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  48779. var scene = this.getScene();
  48780. if (this._options.uniforms.indexOf("world") !== -1) {
  48781. this._effect.setMatrix("world", world);
  48782. }
  48783. if (this._options.uniforms.indexOf("worldView") !== -1) {
  48784. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  48785. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  48786. }
  48787. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  48788. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  48789. }
  48790. };
  48791. ShaderMaterial.prototype.bind = function (world, mesh) {
  48792. // Std values
  48793. this.bindOnlyWorldMatrix(world);
  48794. if (this.getScene().getCachedMaterial() !== this) {
  48795. if (this._options.uniforms.indexOf("view") !== -1) {
  48796. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  48797. }
  48798. if (this._options.uniforms.indexOf("projection") !== -1) {
  48799. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  48800. }
  48801. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  48802. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  48803. }
  48804. // Bones
  48805. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  48806. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48807. }
  48808. var name;
  48809. // Texture
  48810. for (name in this._textures) {
  48811. this._effect.setTexture(name, this._textures[name]);
  48812. }
  48813. // Texture arrays
  48814. for (name in this._textureArrays) {
  48815. this._effect.setTextureArray(name, this._textureArrays[name]);
  48816. }
  48817. // Float
  48818. for (name in this._floats) {
  48819. this._effect.setFloat(name, this._floats[name]);
  48820. }
  48821. // Float s
  48822. for (name in this._floatsArrays) {
  48823. this._effect.setArray(name, this._floatsArrays[name]);
  48824. }
  48825. // Color3
  48826. for (name in this._colors3) {
  48827. this._effect.setColor3(name, this._colors3[name]);
  48828. }
  48829. // Color4
  48830. for (name in this._colors4) {
  48831. var color = this._colors4[name];
  48832. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  48833. }
  48834. // Vector2
  48835. for (name in this._vectors2) {
  48836. this._effect.setVector2(name, this._vectors2[name]);
  48837. }
  48838. // Vector3
  48839. for (name in this._vectors3) {
  48840. this._effect.setVector3(name, this._vectors3[name]);
  48841. }
  48842. // Vector4
  48843. for (name in this._vectors4) {
  48844. this._effect.setVector4(name, this._vectors4[name]);
  48845. }
  48846. // Matrix
  48847. for (name in this._matrices) {
  48848. this._effect.setMatrix(name, this._matrices[name]);
  48849. }
  48850. // Matrix 3x3
  48851. for (name in this._matrices3x3) {
  48852. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  48853. }
  48854. // Matrix 2x2
  48855. for (name in this._matrices2x2) {
  48856. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  48857. }
  48858. }
  48859. _super.prototype.bind.call(this, world, mesh);
  48860. };
  48861. ShaderMaterial.prototype.clone = function (name) {
  48862. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  48863. return newShaderMaterial;
  48864. };
  48865. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  48866. if (forceDisposeTextures) {
  48867. var name;
  48868. for (name in this._textures) {
  48869. this._textures[name].dispose();
  48870. }
  48871. for (name in this._textureArrays) {
  48872. var array = this._textureArrays[name];
  48873. for (var index = 0; index < array.length; index++) {
  48874. array[index].dispose();
  48875. }
  48876. }
  48877. }
  48878. this._textures = {};
  48879. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  48880. };
  48881. ShaderMaterial.prototype.serialize = function () {
  48882. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  48883. serializationObject.customType = "BABYLON.ShaderMaterial";
  48884. serializationObject.options = this._options;
  48885. serializationObject.shaderPath = this._shaderPath;
  48886. var name;
  48887. // Texture
  48888. serializationObject.textures = {};
  48889. for (name in this._textures) {
  48890. serializationObject.textures[name] = this._textures[name].serialize();
  48891. }
  48892. // Texture arrays
  48893. serializationObject.textureArrays = {};
  48894. for (name in this._textureArrays) {
  48895. serializationObject.textureArrays[name] = [];
  48896. var array = this._textureArrays[name];
  48897. for (var index = 0; index < array.length; index++) {
  48898. serializationObject.textureArrays[name].push(array[index].serialize());
  48899. }
  48900. }
  48901. // Float
  48902. serializationObject.floats = {};
  48903. for (name in this._floats) {
  48904. serializationObject.floats[name] = this._floats[name];
  48905. }
  48906. // Float s
  48907. serializationObject.floatArrays = {};
  48908. for (name in this._floatsArrays) {
  48909. serializationObject.floatArrays[name] = this._floatsArrays[name];
  48910. }
  48911. // Color3
  48912. serializationObject.colors3 = {};
  48913. for (name in this._colors3) {
  48914. serializationObject.colors3[name] = this._colors3[name].asArray();
  48915. }
  48916. // Color4
  48917. serializationObject.colors4 = {};
  48918. for (name in this._colors4) {
  48919. serializationObject.colors4[name] = this._colors4[name].asArray();
  48920. }
  48921. // Vector2
  48922. serializationObject.vectors2 = {};
  48923. for (name in this._vectors2) {
  48924. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  48925. }
  48926. // Vector3
  48927. serializationObject.vectors3 = {};
  48928. for (name in this._vectors3) {
  48929. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  48930. }
  48931. // Vector4
  48932. serializationObject.vectors4 = {};
  48933. for (name in this._vectors4) {
  48934. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  48935. }
  48936. // Matrix
  48937. serializationObject.matrices = {};
  48938. for (name in this._matrices) {
  48939. serializationObject.matrices[name] = this._matrices[name].asArray();
  48940. }
  48941. // Matrix 3x3
  48942. serializationObject.matrices3x3 = {};
  48943. for (name in this._matrices3x3) {
  48944. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  48945. }
  48946. // Matrix 2x2
  48947. serializationObject.matrices2x2 = {};
  48948. for (name in this._matrices2x2) {
  48949. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  48950. }
  48951. return serializationObject;
  48952. };
  48953. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  48954. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  48955. var name;
  48956. // Texture
  48957. for (name in source.textures) {
  48958. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  48959. }
  48960. // Texture arrays
  48961. for (name in source.textureArrays) {
  48962. var array = source.textureArrays[name];
  48963. var textureArray = new Array();
  48964. for (var index = 0; index < array.length; index++) {
  48965. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  48966. }
  48967. material.setTextureArray(name, textureArray);
  48968. }
  48969. // Float
  48970. for (name in source.floats) {
  48971. material.setFloat(name, source.floats[name]);
  48972. }
  48973. // Float s
  48974. for (name in source.floatsArrays) {
  48975. material.setFloats(name, source.floatsArrays[name]);
  48976. }
  48977. // Color3
  48978. for (name in source.colors3) {
  48979. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  48980. }
  48981. // Color4
  48982. for (name in source.colors4) {
  48983. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  48984. }
  48985. // Vector2
  48986. for (name in source.vectors2) {
  48987. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  48988. }
  48989. // Vector3
  48990. for (name in source.vectors3) {
  48991. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  48992. }
  48993. // Vector4
  48994. for (name in source.vectors4) {
  48995. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  48996. }
  48997. // Matrix
  48998. for (name in source.matrices) {
  48999. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  49000. }
  49001. // Matrix 3x3
  49002. for (name in source.matrices3x3) {
  49003. material.setMatrix3x3(name, source.matrices3x3[name]);
  49004. }
  49005. // Matrix 2x2
  49006. for (name in source.matrices2x2) {
  49007. material.setMatrix2x2(name, source.matrices2x2[name]);
  49008. }
  49009. return material;
  49010. };
  49011. return ShaderMaterial;
  49012. }(BABYLON.Material));
  49013. BABYLON.ShaderMaterial = ShaderMaterial;
  49014. })(BABYLON || (BABYLON = {}));
  49015. var BABYLON;
  49016. (function (BABYLON) {
  49017. var Internals;
  49018. (function (Internals) {
  49019. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  49020. // All values and structures referenced from:
  49021. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  49022. var DDS_MAGIC = 0x20534444;
  49023. 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;
  49024. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  49025. 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;
  49026. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  49027. function FourCCToInt32(value) {
  49028. return value.charCodeAt(0) +
  49029. (value.charCodeAt(1) << 8) +
  49030. (value.charCodeAt(2) << 16) +
  49031. (value.charCodeAt(3) << 24);
  49032. }
  49033. function Int32ToFourCC(value) {
  49034. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  49035. }
  49036. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  49037. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  49038. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  49039. var headerLengthInt = 31; // The header length in 32 bit ints
  49040. // Offsets into the header array
  49041. var off_magic = 0;
  49042. var off_size = 1;
  49043. var off_flags = 2;
  49044. var off_height = 3;
  49045. var off_width = 4;
  49046. var off_mipmapCount = 7;
  49047. var off_pfFlags = 20;
  49048. var off_pfFourCC = 21;
  49049. var off_RGBbpp = 22;
  49050. var off_RMask = 23;
  49051. var off_GMask = 24;
  49052. var off_BMask = 25;
  49053. var off_AMask = 26;
  49054. var off_caps1 = 27;
  49055. var off_caps2 = 28;
  49056. ;
  49057. var DDSTools = (function () {
  49058. function DDSTools() {
  49059. }
  49060. DDSTools.GetDDSInfo = function (arrayBuffer) {
  49061. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  49062. var mipmapCount = 1;
  49063. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  49064. mipmapCount = Math.max(1, header[off_mipmapCount]);
  49065. }
  49066. return {
  49067. width: header[off_width],
  49068. height: header[off_height],
  49069. mipmapCount: mipmapCount,
  49070. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  49071. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  49072. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  49073. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  49074. };
  49075. };
  49076. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49077. var byteArray = new Uint8Array(dataLength);
  49078. var srcData = new Uint8Array(arrayBuffer);
  49079. var index = 0;
  49080. for (var y = height - 1; y >= 0; y--) {
  49081. for (var x = 0; x < width; x++) {
  49082. var srcPos = dataOffset + (x + y * width) * 4;
  49083. byteArray[index + 2] = srcData[srcPos];
  49084. byteArray[index + 1] = srcData[srcPos + 1];
  49085. byteArray[index] = srcData[srcPos + 2];
  49086. byteArray[index + 3] = srcData[srcPos + 3];
  49087. index += 4;
  49088. }
  49089. }
  49090. return byteArray;
  49091. };
  49092. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49093. var byteArray = new Uint8Array(dataLength);
  49094. var srcData = new Uint8Array(arrayBuffer);
  49095. var index = 0;
  49096. for (var y = height - 1; y >= 0; y--) {
  49097. for (var x = 0; x < width; x++) {
  49098. var srcPos = dataOffset + (x + y * width) * 3;
  49099. byteArray[index + 2] = srcData[srcPos];
  49100. byteArray[index + 1] = srcData[srcPos + 1];
  49101. byteArray[index] = srcData[srcPos + 2];
  49102. index += 3;
  49103. }
  49104. }
  49105. return byteArray;
  49106. };
  49107. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  49108. var byteArray = new Uint8Array(dataLength);
  49109. var srcData = new Uint8Array(arrayBuffer);
  49110. var index = 0;
  49111. for (var y = height - 1; y >= 0; y--) {
  49112. for (var x = 0; x < width; x++) {
  49113. var srcPos = dataOffset + (x + y * width);
  49114. byteArray[index] = srcData[srcPos];
  49115. index++;
  49116. }
  49117. }
  49118. return byteArray;
  49119. };
  49120. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  49121. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  49122. if (header[off_magic] != DDS_MAGIC) {
  49123. BABYLON.Tools.Error("Invalid magic number in DDS header");
  49124. return;
  49125. }
  49126. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  49127. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  49128. return;
  49129. }
  49130. if (info.isFourCC) {
  49131. fourCC = header[off_pfFourCC];
  49132. switch (fourCC) {
  49133. case FOURCC_DXT1:
  49134. blockBytes = 8;
  49135. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  49136. break;
  49137. case FOURCC_DXT3:
  49138. blockBytes = 16;
  49139. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  49140. break;
  49141. case FOURCC_DXT5:
  49142. blockBytes = 16;
  49143. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  49144. break;
  49145. default:
  49146. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  49147. return;
  49148. }
  49149. }
  49150. mipmapCount = 1;
  49151. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  49152. mipmapCount = Math.max(1, header[off_mipmapCount]);
  49153. }
  49154. var bpp = header[off_RGBbpp];
  49155. for (var face = 0; face < faces; face++) {
  49156. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  49157. width = header[off_width];
  49158. height = header[off_height];
  49159. dataOffset = header[off_size] + 4;
  49160. for (i = 0; i < mipmapCount; ++i) {
  49161. if (info.isRGB) {
  49162. if (bpp === 24) {
  49163. dataLength = width * height * 3;
  49164. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49165. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  49166. }
  49167. else {
  49168. dataLength = width * height * 4;
  49169. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49170. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  49171. }
  49172. }
  49173. else if (info.isLuminance) {
  49174. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  49175. var unpaddedRowSize = width;
  49176. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  49177. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  49178. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  49179. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  49180. }
  49181. else {
  49182. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  49183. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  49184. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  49185. }
  49186. dataOffset += dataLength;
  49187. width *= 0.5;
  49188. height *= 0.5;
  49189. width = Math.max(1.0, width);
  49190. height = Math.max(1.0, height);
  49191. }
  49192. }
  49193. };
  49194. return DDSTools;
  49195. }());
  49196. Internals.DDSTools = DDSTools;
  49197. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49198. })(BABYLON || (BABYLON = {}));
  49199. var BABYLON;
  49200. (function (BABYLON) {
  49201. var CannonJSPlugin = (function () {
  49202. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  49203. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  49204. if (iterations === void 0) { iterations = 10; }
  49205. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  49206. this.name = "CannonJSPlugin";
  49207. this._physicsMaterials = [];
  49208. this._fixedTimeStep = 1 / 60;
  49209. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  49210. this._currentCollisionGroup = 2;
  49211. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  49212. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  49213. this._tmpPosition = BABYLON.Vector3.Zero();
  49214. this._tmpQuaternion = new BABYLON.Quaternion();
  49215. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  49216. this._tmpDeltaRotation = new BABYLON.Quaternion();
  49217. this._tmpUnityRotation = new BABYLON.Quaternion();
  49218. if (!this.isSupported()) {
  49219. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  49220. return;
  49221. }
  49222. this.world = new CANNON.World();
  49223. this.world.broadphase = new CANNON.NaiveBroadphase();
  49224. this.world.solver.iterations = iterations;
  49225. }
  49226. CannonJSPlugin.prototype.setGravity = function (gravity) {
  49227. this.world.gravity.copy(gravity);
  49228. };
  49229. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  49230. this._fixedTimeStep = timeStep;
  49231. };
  49232. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  49233. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  49234. };
  49235. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  49236. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  49237. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  49238. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  49239. };
  49240. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  49241. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  49242. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  49243. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  49244. };
  49245. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  49246. //parent-child relationship. Does this impostor has a parent impostor?
  49247. if (impostor.parent) {
  49248. if (impostor.physicsBody) {
  49249. this.removePhysicsBody(impostor);
  49250. //TODO is that needed?
  49251. impostor.forceUpdate();
  49252. }
  49253. return;
  49254. }
  49255. //should a new body be created for this impostor?
  49256. if (impostor.isBodyInitRequired()) {
  49257. var shape = this._createShape(impostor);
  49258. //unregister events, if body is being changed
  49259. var oldBody = impostor.physicsBody;
  49260. if (oldBody) {
  49261. this.removePhysicsBody(impostor);
  49262. }
  49263. //create the body and material
  49264. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  49265. var bodyCreationObject = {
  49266. mass: impostor.getParam("mass"),
  49267. material: material
  49268. };
  49269. // A simple extend, in case native options were used.
  49270. var nativeOptions = impostor.getParam("nativeOptions");
  49271. for (var key in nativeOptions) {
  49272. if (nativeOptions.hasOwnProperty(key)) {
  49273. bodyCreationObject[key] = nativeOptions[key];
  49274. }
  49275. }
  49276. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  49277. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  49278. this.world.addEventListener("preStep", impostor.beforeStep);
  49279. this.world.addEventListener("postStep", impostor.afterStep);
  49280. impostor.physicsBody.addShape(shape);
  49281. this.world.add(impostor.physicsBody);
  49282. //try to keep the body moving in the right direction by taking old properties.
  49283. //Should be tested!
  49284. if (oldBody) {
  49285. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  49286. impostor.physicsBody[param].copy(oldBody[param]);
  49287. });
  49288. }
  49289. this._processChildMeshes(impostor);
  49290. }
  49291. //now update the body's transformation
  49292. this._updatePhysicsBodyTransformation(impostor);
  49293. };
  49294. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  49295. var _this = this;
  49296. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  49297. if (meshChildren.length) {
  49298. var processMesh = function (localPosition, mesh) {
  49299. var childImpostor = mesh.getPhysicsImpostor();
  49300. if (childImpostor) {
  49301. var parent = childImpostor.parent;
  49302. if (parent !== mainImpostor) {
  49303. var localPosition = mesh.position;
  49304. if (childImpostor.physicsBody) {
  49305. _this.removePhysicsBody(childImpostor);
  49306. childImpostor.physicsBody = null;
  49307. }
  49308. childImpostor.parent = mainImpostor;
  49309. childImpostor.resetUpdateFlags();
  49310. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  49311. //Add the mass of the children.
  49312. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  49313. }
  49314. }
  49315. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  49316. };
  49317. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  49318. }
  49319. };
  49320. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  49321. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  49322. this.world.removeEventListener("preStep", impostor.beforeStep);
  49323. this.world.removeEventListener("postStep", impostor.afterStep);
  49324. this.world.remove(impostor.physicsBody);
  49325. };
  49326. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  49327. var mainBody = impostorJoint.mainImpostor.physicsBody;
  49328. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  49329. if (!mainBody || !connectedBody) {
  49330. return;
  49331. }
  49332. var constraint;
  49333. var jointData = impostorJoint.joint.jointData;
  49334. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  49335. var constraintData = {
  49336. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  49337. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  49338. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  49339. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  49340. maxForce: jointData.nativeParams.maxForce,
  49341. collideConnected: !!jointData.collision
  49342. };
  49343. //Not needed, Cannon has a collideConnected flag
  49344. /*if (!jointData.collision) {
  49345. //add 1st body to a collision group of its own, if it is not in 1
  49346. if (mainBody.collisionFilterGroup === 1) {
  49347. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  49348. this._currentCollisionGroup <<= 1;
  49349. }
  49350. if (connectedBody.collisionFilterGroup === 1) {
  49351. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  49352. this._currentCollisionGroup <<= 1;
  49353. }
  49354. //add their mask to the collisionFilterMask of each other:
  49355. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  49356. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  49357. }*/
  49358. switch (impostorJoint.joint.type) {
  49359. case BABYLON.PhysicsJoint.HingeJoint:
  49360. case BABYLON.PhysicsJoint.Hinge2Joint:
  49361. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  49362. break;
  49363. case BABYLON.PhysicsJoint.DistanceJoint:
  49364. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  49365. break;
  49366. case BABYLON.PhysicsJoint.SpringJoint:
  49367. var springData = jointData;
  49368. constraint = new CANNON.Spring(mainBody, connectedBody, {
  49369. restLength: springData.length,
  49370. stiffness: springData.stiffness,
  49371. damping: springData.damping,
  49372. localAnchorA: constraintData.pivotA,
  49373. localAnchorB: constraintData.pivotB
  49374. });
  49375. break;
  49376. case BABYLON.PhysicsJoint.LockJoint:
  49377. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  49378. break;
  49379. case BABYLON.PhysicsJoint.PointToPointJoint:
  49380. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  49381. default:
  49382. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  49383. break;
  49384. }
  49385. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  49386. constraint.collideConnected = !!jointData.collision;
  49387. impostorJoint.joint.physicsJoint = constraint;
  49388. //don't add spring as constraint, as it is not one.
  49389. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  49390. this.world.addConstraint(constraint);
  49391. }
  49392. else {
  49393. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  49394. constraint.applyForce();
  49395. });
  49396. }
  49397. };
  49398. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  49399. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  49400. };
  49401. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  49402. var index;
  49403. var mat;
  49404. for (index = 0; index < this._physicsMaterials.length; index++) {
  49405. mat = this._physicsMaterials[index];
  49406. if (mat.friction === friction && mat.restitution === restitution) {
  49407. return mat;
  49408. }
  49409. }
  49410. var currentMat = new CANNON.Material(name);
  49411. currentMat.friction = friction;
  49412. currentMat.restitution = restitution;
  49413. this._physicsMaterials.push(currentMat);
  49414. return currentMat;
  49415. };
  49416. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  49417. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  49418. };
  49419. CannonJSPlugin.prototype._createShape = function (impostor) {
  49420. var object = impostor.object;
  49421. var returnValue;
  49422. var extendSize = impostor.getObjectExtendSize();
  49423. switch (impostor.type) {
  49424. case BABYLON.PhysicsEngine.SphereImpostor:
  49425. var radiusX = extendSize.x;
  49426. var radiusY = extendSize.y;
  49427. var radiusZ = extendSize.z;
  49428. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  49429. break;
  49430. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  49431. case BABYLON.PhysicsImpostor.CylinderImpostor:
  49432. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  49433. break;
  49434. case BABYLON.PhysicsImpostor.BoxImpostor:
  49435. var box = extendSize.scale(0.5);
  49436. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  49437. break;
  49438. case BABYLON.PhysicsImpostor.PlaneImpostor:
  49439. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  49440. returnValue = new CANNON.Plane();
  49441. break;
  49442. case BABYLON.PhysicsImpostor.MeshImpostor:
  49443. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  49444. var rawFaces = object.getIndices ? object.getIndices() : [];
  49445. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  49446. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  49447. break;
  49448. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  49449. returnValue = this._createHeightmap(object);
  49450. break;
  49451. case BABYLON.PhysicsImpostor.ParticleImpostor:
  49452. returnValue = new CANNON.Particle();
  49453. break;
  49454. }
  49455. return returnValue;
  49456. };
  49457. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  49458. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49459. var matrix = [];
  49460. //For now pointDepth will not be used and will be automatically calculated.
  49461. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  49462. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  49463. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  49464. var elementSize = dim * 2 / arraySize;
  49465. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  49466. for (var i = 0; i < pos.length; i = i + 3) {
  49467. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  49468. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  49469. var y = pos[i + 1] + minY;
  49470. if (!matrix[x]) {
  49471. matrix[x] = [];
  49472. }
  49473. if (!matrix[x][z]) {
  49474. matrix[x][z] = y;
  49475. }
  49476. matrix[x][z] = Math.max(y, matrix[x][z]);
  49477. }
  49478. for (var x = 0; x <= arraySize; ++x) {
  49479. if (!matrix[x]) {
  49480. var loc = 1;
  49481. while (!matrix[(x + loc) % arraySize]) {
  49482. loc++;
  49483. }
  49484. matrix[x] = matrix[(x + loc) % arraySize].slice();
  49485. }
  49486. for (var z = 0; z <= arraySize; ++z) {
  49487. if (!matrix[x][z]) {
  49488. var loc = 1;
  49489. var newValue;
  49490. while (newValue === undefined) {
  49491. newValue = matrix[x][(z + loc++) % arraySize];
  49492. }
  49493. matrix[x][z] = newValue;
  49494. }
  49495. }
  49496. }
  49497. var shape = new CANNON.Heightfield(matrix, {
  49498. elementSize: elementSize
  49499. });
  49500. //For future reference, needed for body transformation
  49501. shape.minY = minY;
  49502. return shape;
  49503. };
  49504. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  49505. var object = impostor.object;
  49506. //make sure it is updated...
  49507. object.computeWorldMatrix && object.computeWorldMatrix(true);
  49508. // The delta between the mesh position and the mesh bounding box center
  49509. var center = impostor.getObjectCenter();
  49510. var extendSize = impostor.getObjectExtendSize();
  49511. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  49512. this._tmpPosition.copyFrom(center);
  49513. var quaternion = object.rotationQuaternion;
  49514. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  49515. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  49516. //-90 DEG in X, precalculated
  49517. quaternion = quaternion.multiply(this._minus90X);
  49518. //Invert! (Precalculated, 90 deg in X)
  49519. //No need to clone. this will never change.
  49520. impostor.setDeltaRotation(this._plus90X);
  49521. }
  49522. //If it is a heightfield, if should be centered.
  49523. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  49524. var mesh = object;
  49525. //calculate the correct body position:
  49526. var rotationQuaternion = mesh.rotationQuaternion;
  49527. mesh.rotationQuaternion = this._tmpUnityRotation;
  49528. mesh.computeWorldMatrix(true);
  49529. //get original center with no rotation
  49530. var c = center.clone();
  49531. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  49532. //rotation is back
  49533. mesh.rotationQuaternion = rotationQuaternion;
  49534. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  49535. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  49536. mesh.setPivotMatrix(p);
  49537. mesh.computeWorldMatrix(true);
  49538. //calculate the translation
  49539. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  49540. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  49541. //add it inverted to the delta
  49542. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  49543. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  49544. mesh.setPivotMatrix(oldPivot);
  49545. mesh.computeWorldMatrix(true);
  49546. }
  49547. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  49548. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  49549. this._tmpPosition.copyFrom(object.position);
  49550. }
  49551. impostor.setDeltaPosition(this._tmpDeltaPosition);
  49552. //Now update the impostor object
  49553. impostor.physicsBody.position.copy(this._tmpPosition);
  49554. impostor.physicsBody.quaternion.copy(quaternion);
  49555. };
  49556. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  49557. impostor.object.position.copyFrom(impostor.physicsBody.position);
  49558. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  49559. };
  49560. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  49561. impostor.physicsBody.position.copy(newPosition);
  49562. impostor.physicsBody.quaternion.copy(newRotation);
  49563. };
  49564. CannonJSPlugin.prototype.isSupported = function () {
  49565. return window.CANNON !== undefined;
  49566. };
  49567. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  49568. impostor.physicsBody.velocity.copy(velocity);
  49569. };
  49570. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  49571. impostor.physicsBody.angularVelocity.copy(velocity);
  49572. };
  49573. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  49574. var v = impostor.physicsBody.velocity;
  49575. if (!v)
  49576. return null;
  49577. return new BABYLON.Vector3(v.x, v.y, v.z);
  49578. };
  49579. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  49580. var v = impostor.physicsBody.angularVelocity;
  49581. if (!v)
  49582. return null;
  49583. return new BABYLON.Vector3(v.x, v.y, v.z);
  49584. };
  49585. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  49586. impostor.physicsBody.mass = mass;
  49587. impostor.physicsBody.updateMassProperties();
  49588. };
  49589. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  49590. impostor.physicsBody.sleep();
  49591. };
  49592. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  49593. impostor.physicsBody.wakeUp();
  49594. };
  49595. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  49596. joint.physicsJoint.distance = maxDistance;
  49597. };
  49598. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  49599. if (!motorIndex) {
  49600. joint.physicsJoint.enableMotor();
  49601. }
  49602. };
  49603. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  49604. if (!motorIndex) {
  49605. joint.physicsJoint.disableMotor();
  49606. }
  49607. };
  49608. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  49609. if (!motorIndex) {
  49610. joint.physicsJoint.enableMotor();
  49611. joint.physicsJoint.setMotorSpeed(speed);
  49612. if (maxForce) {
  49613. this.setLimit(joint, maxForce);
  49614. }
  49615. }
  49616. };
  49617. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  49618. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  49619. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  49620. };
  49621. CannonJSPlugin.prototype.dispose = function () {
  49622. //nothing to do, actually.
  49623. };
  49624. return CannonJSPlugin;
  49625. }());
  49626. BABYLON.CannonJSPlugin = CannonJSPlugin;
  49627. })(BABYLON || (BABYLON = {}));
  49628. var BABYLON;
  49629. (function (BABYLON) {
  49630. var OimoJSPlugin = (function () {
  49631. function OimoJSPlugin(iterations) {
  49632. this.name = "OimoJSPlugin";
  49633. this._tmpImpostorsArray = [];
  49634. this._tmpPositionVector = BABYLON.Vector3.Zero();
  49635. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  49636. this.world.clear();
  49637. //making sure no stats are calculated
  49638. this.world.isNoStat = true;
  49639. }
  49640. OimoJSPlugin.prototype.setGravity = function (gravity) {
  49641. this.world.gravity.copy(gravity);
  49642. };
  49643. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  49644. this.world.timeStep = timeStep;
  49645. };
  49646. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  49647. var _this = this;
  49648. impostors.forEach(function (impostor) {
  49649. impostor.beforeStep();
  49650. });
  49651. this.world.step();
  49652. impostors.forEach(function (impostor) {
  49653. impostor.afterStep();
  49654. //update the ordered impostors array
  49655. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  49656. });
  49657. //check for collisions
  49658. var contact = this.world.contacts;
  49659. while (contact !== null) {
  49660. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  49661. contact = contact.next;
  49662. continue;
  49663. }
  49664. //is this body colliding with any other? get the impostor
  49665. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  49666. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  49667. if (!mainImpostor || !collidingImpostor) {
  49668. contact = contact.next;
  49669. continue;
  49670. }
  49671. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  49672. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  49673. contact = contact.next;
  49674. }
  49675. };
  49676. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  49677. var mass = impostor.physicsBody.massInfo.mass;
  49678. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  49679. };
  49680. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  49681. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  49682. this.applyImpulse(impostor, force, contactPoint);
  49683. };
  49684. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  49685. var _this = this;
  49686. //parent-child relationship. Does this impostor has a parent impostor?
  49687. if (impostor.parent) {
  49688. if (impostor.physicsBody) {
  49689. this.removePhysicsBody(impostor);
  49690. //TODO is that needed?
  49691. impostor.forceUpdate();
  49692. }
  49693. return;
  49694. }
  49695. if (impostor.isBodyInitRequired()) {
  49696. var bodyConfig = {
  49697. name: impostor.uniqueId,
  49698. //Oimo must have mass, also for static objects.
  49699. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  49700. size: [],
  49701. type: [],
  49702. pos: [],
  49703. rot: [],
  49704. move: impostor.getParam("mass") !== 0,
  49705. //Supporting older versions of Oimo
  49706. world: this.world
  49707. };
  49708. var impostors = [impostor];
  49709. function addToArray(parent) {
  49710. if (!parent.getChildMeshes)
  49711. return;
  49712. parent.getChildMeshes().forEach(function (m) {
  49713. if (m.physicsImpostor) {
  49714. impostors.push(m.physicsImpostor);
  49715. m.physicsImpostor._init();
  49716. }
  49717. });
  49718. }
  49719. addToArray(impostor.object);
  49720. function checkWithEpsilon(value) {
  49721. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  49722. }
  49723. impostors.forEach(function (i) {
  49724. //get the correct bounding box
  49725. var oldQuaternion = i.object.rotationQuaternion;
  49726. var rot = new OIMO.Euler().setFromQuaternion({
  49727. x: impostor.object.rotationQuaternion.x,
  49728. y: impostor.object.rotationQuaternion.y,
  49729. z: impostor.object.rotationQuaternion.z,
  49730. s: impostor.object.rotationQuaternion.w
  49731. });
  49732. var extendSize = i.getObjectExtendSize();
  49733. if (i === impostor) {
  49734. var center = impostor.getObjectCenter();
  49735. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  49736. //Can also use Array.prototype.push.apply
  49737. bodyConfig.pos.push(center.x);
  49738. bodyConfig.pos.push(center.y);
  49739. bodyConfig.pos.push(center.z);
  49740. //tmp solution
  49741. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  49742. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  49743. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  49744. }
  49745. else {
  49746. bodyConfig.pos.push(i.object.position.x);
  49747. bodyConfig.pos.push(i.object.position.y);
  49748. bodyConfig.pos.push(i.object.position.z);
  49749. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  49750. bodyConfig.rot.push(0);
  49751. bodyConfig.rot.push(0);
  49752. bodyConfig.rot.push(0);
  49753. }
  49754. // register mesh
  49755. switch (i.type) {
  49756. case BABYLON.PhysicsImpostor.ParticleImpostor:
  49757. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  49758. case BABYLON.PhysicsImpostor.SphereImpostor:
  49759. var radiusX = extendSize.x;
  49760. var radiusY = extendSize.y;
  49761. var radiusZ = extendSize.z;
  49762. var size = Math.max(checkWithEpsilon(radiusX), checkWithEpsilon(radiusY), checkWithEpsilon(radiusZ)) / 2;
  49763. bodyConfig.type.push('sphere');
  49764. //due to the way oimo works with compounds, add 3 times
  49765. bodyConfig.size.push(size);
  49766. bodyConfig.size.push(size);
  49767. bodyConfig.size.push(size);
  49768. break;
  49769. case BABYLON.PhysicsImpostor.CylinderImpostor:
  49770. var sizeX = checkWithEpsilon(extendSize.x) / 2;
  49771. var sizeY = checkWithEpsilon(extendSize.y);
  49772. bodyConfig.type.push('cylinder');
  49773. bodyConfig.size.push(sizeX);
  49774. bodyConfig.size.push(sizeY);
  49775. //due to the way oimo works with compounds, add one more value.
  49776. bodyConfig.size.push(sizeY);
  49777. break;
  49778. case BABYLON.PhysicsImpostor.PlaneImpostor:
  49779. case BABYLON.PhysicsImpostor.BoxImpostor:
  49780. default:
  49781. var sizeX = checkWithEpsilon(extendSize.x);
  49782. var sizeY = checkWithEpsilon(extendSize.y);
  49783. var sizeZ = checkWithEpsilon(extendSize.z);
  49784. bodyConfig.type.push('box');
  49785. bodyConfig.size.push(sizeX);
  49786. bodyConfig.size.push(sizeY);
  49787. bodyConfig.size.push(sizeZ);
  49788. break;
  49789. }
  49790. //actually not needed, but hey...
  49791. i.object.rotationQuaternion = oldQuaternion;
  49792. });
  49793. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  49794. }
  49795. else {
  49796. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  49797. }
  49798. impostor.setDeltaPosition(this._tmpPositionVector);
  49799. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  49800. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  49801. };
  49802. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  49803. //impostor.physicsBody.dispose();
  49804. //Same as : (older oimo versions)
  49805. this.world.removeRigidBody(impostor.physicsBody);
  49806. };
  49807. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  49808. var mainBody = impostorJoint.mainImpostor.physicsBody;
  49809. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  49810. if (!mainBody || !connectedBody) {
  49811. return;
  49812. }
  49813. var jointData = impostorJoint.joint.jointData;
  49814. var options = jointData.nativeParams || {};
  49815. var type;
  49816. var nativeJointData = {
  49817. body1: mainBody,
  49818. body2: connectedBody,
  49819. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  49820. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  49821. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  49822. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  49823. min: options.min,
  49824. max: options.max,
  49825. collision: options.collision || jointData.collision,
  49826. spring: options.spring,
  49827. //supporting older version of Oimo
  49828. world: this.world
  49829. };
  49830. switch (impostorJoint.joint.type) {
  49831. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  49832. type = "jointBall";
  49833. break;
  49834. case BABYLON.PhysicsJoint.SpringJoint:
  49835. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  49836. var springData = jointData;
  49837. nativeJointData.min = springData.length || nativeJointData.min;
  49838. //Max should also be set, just make sure it is at least min
  49839. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  49840. case BABYLON.PhysicsJoint.DistanceJoint:
  49841. type = "jointDistance";
  49842. nativeJointData.max = jointData.maxDistance;
  49843. break;
  49844. case BABYLON.PhysicsJoint.PrismaticJoint:
  49845. type = "jointPrisme";
  49846. break;
  49847. case BABYLON.PhysicsJoint.SliderJoint:
  49848. type = "jointSlide";
  49849. break;
  49850. case BABYLON.PhysicsJoint.WheelJoint:
  49851. type = "jointWheel";
  49852. break;
  49853. case BABYLON.PhysicsJoint.HingeJoint:
  49854. default:
  49855. type = "jointHinge";
  49856. break;
  49857. }
  49858. nativeJointData.type = type;
  49859. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  49860. };
  49861. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  49862. //Bug in Oimo prevents us from disposing a joint in the playground
  49863. //joint.joint.physicsJoint.dispose();
  49864. //So we will bruteforce it!
  49865. try {
  49866. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  49867. }
  49868. catch (e) {
  49869. BABYLON.Tools.Warn(e);
  49870. }
  49871. };
  49872. OimoJSPlugin.prototype.isSupported = function () {
  49873. return OIMO !== undefined;
  49874. };
  49875. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  49876. if (!impostor.physicsBody.sleeping) {
  49877. //TODO check that
  49878. if (impostor.physicsBody.shapes.next) {
  49879. var parentShape = this._getLastShape(impostor.physicsBody);
  49880. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  49881. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  49882. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  49883. }
  49884. else {
  49885. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  49886. }
  49887. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  49888. impostor.object.rotationQuaternion.normalize();
  49889. }
  49890. };
  49891. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  49892. var body = impostor.physicsBody;
  49893. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  49894. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  49895. body.syncShapes();
  49896. body.awake();
  49897. };
  49898. OimoJSPlugin.prototype._getLastShape = function (body) {
  49899. var lastShape = body.shapes;
  49900. while (lastShape.next) {
  49901. lastShape = lastShape.next;
  49902. }
  49903. return lastShape;
  49904. };
  49905. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  49906. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  49907. };
  49908. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  49909. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  49910. };
  49911. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  49912. var v = impostor.physicsBody.linearVelocity;
  49913. if (!v)
  49914. return null;
  49915. return new BABYLON.Vector3(v.x, v.y, v.z);
  49916. };
  49917. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  49918. var v = impostor.physicsBody.angularVelocity;
  49919. if (!v)
  49920. return null;
  49921. return new BABYLON.Vector3(v.x, v.y, v.z);
  49922. };
  49923. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  49924. var staticBody = mass === 0;
  49925. //this will actually set the body's density and not its mass.
  49926. //But this is how oimo treats the mass variable.
  49927. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  49928. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  49929. };
  49930. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  49931. impostor.physicsBody.sleep();
  49932. };
  49933. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  49934. impostor.physicsBody.awake();
  49935. };
  49936. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  49937. joint.physicsJoint.limitMotoe.upperLimit = maxDistance;
  49938. if (minDistance !== void 0) {
  49939. joint.physicsJoint.limitMotoe.lowerLimit = minDistance;
  49940. }
  49941. };
  49942. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  49943. //TODO separate rotational and transational motors.
  49944. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  49945. if (motor) {
  49946. motor.setMotor(speed, maxForce);
  49947. }
  49948. };
  49949. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  49950. //TODO separate rotational and transational motors.
  49951. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  49952. if (motor) {
  49953. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  49954. }
  49955. };
  49956. OimoJSPlugin.prototype.dispose = function () {
  49957. this.world.clear();
  49958. };
  49959. return OimoJSPlugin;
  49960. }());
  49961. BABYLON.OimoJSPlugin = OimoJSPlugin;
  49962. })(BABYLON || (BABYLON = {}));
  49963. var BABYLON;
  49964. (function (BABYLON) {
  49965. var DisplayPassPostProcess = (function (_super) {
  49966. __extends(DisplayPassPostProcess, _super);
  49967. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  49968. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  49969. }
  49970. return DisplayPassPostProcess;
  49971. }(BABYLON.PostProcess));
  49972. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  49973. })(BABYLON || (BABYLON = {}));
  49974. var BABYLON;
  49975. (function (BABYLON) {
  49976. var SimplificationSettings = (function () {
  49977. function SimplificationSettings(quality, distance, optimizeMesh) {
  49978. this.quality = quality;
  49979. this.distance = distance;
  49980. this.optimizeMesh = optimizeMesh;
  49981. }
  49982. return SimplificationSettings;
  49983. }());
  49984. BABYLON.SimplificationSettings = SimplificationSettings;
  49985. var SimplificationQueue = (function () {
  49986. function SimplificationQueue() {
  49987. this.running = false;
  49988. this._simplificationArray = [];
  49989. }
  49990. SimplificationQueue.prototype.addTask = function (task) {
  49991. this._simplificationArray.push(task);
  49992. };
  49993. SimplificationQueue.prototype.executeNext = function () {
  49994. var task = this._simplificationArray.pop();
  49995. if (task) {
  49996. this.running = true;
  49997. this.runSimplification(task);
  49998. }
  49999. else {
  50000. this.running = false;
  50001. }
  50002. };
  50003. SimplificationQueue.prototype.runSimplification = function (task) {
  50004. var _this = this;
  50005. if (task.parallelProcessing) {
  50006. //parallel simplifier
  50007. task.settings.forEach(function (setting) {
  50008. var simplifier = _this.getSimplifier(task);
  50009. simplifier.simplify(setting, function (newMesh) {
  50010. task.mesh.addLODLevel(setting.distance, newMesh);
  50011. newMesh.isVisible = true;
  50012. //check if it is the last
  50013. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  50014. //all done, run the success callback.
  50015. task.successCallback();
  50016. }
  50017. _this.executeNext();
  50018. });
  50019. });
  50020. }
  50021. else {
  50022. //single simplifier.
  50023. var simplifier = this.getSimplifier(task);
  50024. var runDecimation = function (setting, callback) {
  50025. simplifier.simplify(setting, function (newMesh) {
  50026. task.mesh.addLODLevel(setting.distance, newMesh);
  50027. newMesh.isVisible = true;
  50028. //run the next quality level
  50029. callback();
  50030. });
  50031. };
  50032. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  50033. runDecimation(task.settings[loop.index], function () {
  50034. loop.executeNext();
  50035. });
  50036. }, function () {
  50037. //execution ended, run the success callback.
  50038. if (task.successCallback) {
  50039. task.successCallback();
  50040. }
  50041. _this.executeNext();
  50042. });
  50043. }
  50044. };
  50045. SimplificationQueue.prototype.getSimplifier = function (task) {
  50046. switch (task.simplificationType) {
  50047. case SimplificationType.QUADRATIC:
  50048. default:
  50049. return new QuadraticErrorSimplification(task.mesh);
  50050. }
  50051. };
  50052. return SimplificationQueue;
  50053. }());
  50054. BABYLON.SimplificationQueue = SimplificationQueue;
  50055. /**
  50056. * The implemented types of simplification.
  50057. * At the moment only Quadratic Error Decimation is implemented.
  50058. */
  50059. (function (SimplificationType) {
  50060. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  50061. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  50062. var SimplificationType = BABYLON.SimplificationType;
  50063. var DecimationTriangle = (function () {
  50064. function DecimationTriangle(vertices) {
  50065. this.vertices = vertices;
  50066. this.error = new Array(4);
  50067. this.deleted = false;
  50068. this.isDirty = false;
  50069. this.deletePending = false;
  50070. this.borderFactor = 0;
  50071. }
  50072. return DecimationTriangle;
  50073. }());
  50074. BABYLON.DecimationTriangle = DecimationTriangle;
  50075. var DecimationVertex = (function () {
  50076. function DecimationVertex(position, id) {
  50077. this.position = position;
  50078. this.id = id;
  50079. this.isBorder = true;
  50080. this.q = new QuadraticMatrix();
  50081. this.triangleCount = 0;
  50082. this.triangleStart = 0;
  50083. this.originalOffsets = [];
  50084. }
  50085. DecimationVertex.prototype.updatePosition = function (newPosition) {
  50086. this.position.copyFrom(newPosition);
  50087. };
  50088. return DecimationVertex;
  50089. }());
  50090. BABYLON.DecimationVertex = DecimationVertex;
  50091. var QuadraticMatrix = (function () {
  50092. function QuadraticMatrix(data) {
  50093. this.data = new Array(10);
  50094. for (var i = 0; i < 10; ++i) {
  50095. if (data && data[i]) {
  50096. this.data[i] = data[i];
  50097. }
  50098. else {
  50099. this.data[i] = 0;
  50100. }
  50101. }
  50102. }
  50103. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  50104. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  50105. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  50106. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  50107. return det;
  50108. };
  50109. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  50110. for (var i = 0; i < 10; ++i) {
  50111. this.data[i] += matrix.data[i];
  50112. }
  50113. };
  50114. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  50115. for (var i = 0; i < 10; ++i) {
  50116. this.data[i] += data[i];
  50117. }
  50118. };
  50119. QuadraticMatrix.prototype.add = function (matrix) {
  50120. var m = new QuadraticMatrix();
  50121. for (var i = 0; i < 10; ++i) {
  50122. m.data[i] = this.data[i] + matrix.data[i];
  50123. }
  50124. return m;
  50125. };
  50126. QuadraticMatrix.FromData = function (a, b, c, d) {
  50127. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  50128. };
  50129. //returning an array to avoid garbage collection
  50130. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  50131. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  50132. };
  50133. return QuadraticMatrix;
  50134. }());
  50135. BABYLON.QuadraticMatrix = QuadraticMatrix;
  50136. var Reference = (function () {
  50137. function Reference(vertexId, triangleId) {
  50138. this.vertexId = vertexId;
  50139. this.triangleId = triangleId;
  50140. }
  50141. return Reference;
  50142. }());
  50143. BABYLON.Reference = Reference;
  50144. /**
  50145. * An implementation of the Quadratic Error simplification algorithm.
  50146. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  50147. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  50148. * @author RaananW
  50149. */
  50150. var QuadraticErrorSimplification = (function () {
  50151. function QuadraticErrorSimplification(_mesh) {
  50152. this._mesh = _mesh;
  50153. this.initialized = false;
  50154. this.syncIterations = 5000;
  50155. this.aggressiveness = 7;
  50156. this.decimationIterations = 100;
  50157. this.boundingBoxEpsilon = BABYLON.Epsilon;
  50158. }
  50159. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  50160. var _this = this;
  50161. this.initDecimatedMesh();
  50162. //iterating through the submeshes array, one after the other.
  50163. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  50164. _this.initWithMesh(loop.index, function () {
  50165. _this.runDecimation(settings, loop.index, function () {
  50166. loop.executeNext();
  50167. });
  50168. }, settings.optimizeMesh);
  50169. }, function () {
  50170. setTimeout(function () {
  50171. successCallback(_this._reconstructedMesh);
  50172. }, 0);
  50173. });
  50174. };
  50175. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  50176. var _this = this;
  50177. var gCount = 0;
  50178. triangle.vertices.forEach(function (vertex) {
  50179. var count = 0;
  50180. var vPos = vertex.position;
  50181. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  50182. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  50183. ++count;
  50184. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  50185. ++count;
  50186. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  50187. ++count;
  50188. if (count > 1) {
  50189. ++gCount;
  50190. }
  50191. ;
  50192. });
  50193. if (gCount > 1) {
  50194. console.log(triangle, gCount);
  50195. }
  50196. return gCount > 1;
  50197. };
  50198. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  50199. var _this = this;
  50200. var targetCount = ~~(this.triangles.length * settings.quality);
  50201. var deletedTriangles = 0;
  50202. var triangleCount = this.triangles.length;
  50203. var iterationFunction = function (iteration, callback) {
  50204. setTimeout(function () {
  50205. if (iteration % 5 === 0) {
  50206. _this.updateMesh(iteration === 0);
  50207. }
  50208. for (var i = 0; i < _this.triangles.length; ++i) {
  50209. _this.triangles[i].isDirty = false;
  50210. }
  50211. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  50212. var trianglesIterator = function (i) {
  50213. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  50214. var t = _this.triangles[tIdx];
  50215. if (!t)
  50216. return;
  50217. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  50218. return;
  50219. }
  50220. for (var j = 0; j < 3; ++j) {
  50221. if (t.error[j] < threshold) {
  50222. var deleted0 = [];
  50223. var deleted1 = [];
  50224. var v0 = t.vertices[j];
  50225. var v1 = t.vertices[(j + 1) % 3];
  50226. if (v0.isBorder || v1.isBorder)
  50227. continue;
  50228. var p = BABYLON.Vector3.Zero();
  50229. var n = BABYLON.Vector3.Zero();
  50230. var uv = BABYLON.Vector2.Zero();
  50231. var color = new BABYLON.Color4(0, 0, 0, 1);
  50232. _this.calculateError(v0, v1, p, n, uv, color);
  50233. var delTr = [];
  50234. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  50235. continue;
  50236. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  50237. continue;
  50238. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  50239. continue;
  50240. var uniqueArray = [];
  50241. delTr.forEach(function (deletedT) {
  50242. if (uniqueArray.indexOf(deletedT) === -1) {
  50243. deletedT.deletePending = true;
  50244. uniqueArray.push(deletedT);
  50245. }
  50246. });
  50247. if (uniqueArray.length % 2 !== 0) {
  50248. continue;
  50249. }
  50250. v0.q = v1.q.add(v0.q);
  50251. v0.updatePosition(p);
  50252. var tStart = _this.references.length;
  50253. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  50254. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  50255. var tCount = _this.references.length - tStart;
  50256. if (tCount <= v0.triangleCount) {
  50257. if (tCount) {
  50258. for (var c = 0; c < tCount; c++) {
  50259. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  50260. }
  50261. }
  50262. }
  50263. else {
  50264. v0.triangleStart = tStart;
  50265. }
  50266. v0.triangleCount = tCount;
  50267. break;
  50268. }
  50269. }
  50270. };
  50271. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  50272. }, 0);
  50273. };
  50274. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  50275. if (triangleCount - deletedTriangles <= targetCount)
  50276. loop.breakLoop();
  50277. else {
  50278. iterationFunction(loop.index, function () {
  50279. loop.executeNext();
  50280. });
  50281. }
  50282. }, function () {
  50283. setTimeout(function () {
  50284. //reconstruct this part of the mesh
  50285. _this.reconstructMesh(submeshIndex);
  50286. successCallback();
  50287. }, 0);
  50288. });
  50289. };
  50290. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  50291. var _this = this;
  50292. this.vertices = [];
  50293. this.triangles = [];
  50294. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50295. var indices = this._mesh.getIndices();
  50296. var submesh = this._mesh.subMeshes[submeshIndex];
  50297. var findInVertices = function (positionToSearch) {
  50298. if (optimizeMesh) {
  50299. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  50300. if (_this.vertices[ii].position.equals(positionToSearch)) {
  50301. return _this.vertices[ii];
  50302. }
  50303. }
  50304. }
  50305. return null;
  50306. };
  50307. var vertexReferences = [];
  50308. var vertexInit = function (i) {
  50309. var offset = i + submesh.verticesStart;
  50310. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  50311. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  50312. vertex.originalOffsets.push(offset);
  50313. if (vertex.id === _this.vertices.length) {
  50314. _this.vertices.push(vertex);
  50315. }
  50316. vertexReferences.push(vertex.id);
  50317. };
  50318. //var totalVertices = mesh.getTotalVertices();
  50319. var totalVertices = submesh.verticesCount;
  50320. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  50321. var indicesInit = function (i) {
  50322. var offset = (submesh.indexStart / 3) + i;
  50323. var pos = (offset * 3);
  50324. var i0 = indices[pos + 0];
  50325. var i1 = indices[pos + 1];
  50326. var i2 = indices[pos + 2];
  50327. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  50328. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  50329. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  50330. var triangle = new DecimationTriangle([v0, v1, v2]);
  50331. triangle.originalOffset = pos;
  50332. _this.triangles.push(triangle);
  50333. };
  50334. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  50335. _this.init(callback);
  50336. });
  50337. });
  50338. };
  50339. QuadraticErrorSimplification.prototype.init = function (callback) {
  50340. var _this = this;
  50341. var triangleInit1 = function (i) {
  50342. var t = _this.triangles[i];
  50343. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  50344. for (var j = 0; j < 3; j++) {
  50345. 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))));
  50346. }
  50347. };
  50348. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  50349. var triangleInit2 = function (i) {
  50350. var t = _this.triangles[i];
  50351. for (var j = 0; j < 3; ++j) {
  50352. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  50353. }
  50354. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  50355. };
  50356. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  50357. _this.initialized = true;
  50358. callback();
  50359. });
  50360. });
  50361. };
  50362. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  50363. var newTriangles = [];
  50364. var i;
  50365. for (i = 0; i < this.vertices.length; ++i) {
  50366. this.vertices[i].triangleCount = 0;
  50367. }
  50368. var t;
  50369. var j;
  50370. for (i = 0; i < this.triangles.length; ++i) {
  50371. if (!this.triangles[i].deleted) {
  50372. t = this.triangles[i];
  50373. for (j = 0; j < 3; ++j) {
  50374. t.vertices[j].triangleCount = 1;
  50375. }
  50376. newTriangles.push(t);
  50377. }
  50378. }
  50379. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  50380. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  50381. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  50382. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  50383. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50384. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50385. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50386. var vertexCount = 0;
  50387. for (i = 0; i < this.vertices.length; ++i) {
  50388. var vertex = this.vertices[i];
  50389. vertex.id = vertexCount;
  50390. if (vertex.triangleCount) {
  50391. vertex.originalOffsets.forEach(function (originalOffset) {
  50392. newPositionData.push(vertex.position.x);
  50393. newPositionData.push(vertex.position.y);
  50394. newPositionData.push(vertex.position.z);
  50395. newNormalData.push(normalData[originalOffset * 3]);
  50396. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  50397. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  50398. if (uvs && uvs.length) {
  50399. newUVsData.push(uvs[(originalOffset * 2)]);
  50400. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  50401. }
  50402. else if (colorsData && colorsData.length) {
  50403. newColorsData.push(colorsData[(originalOffset * 4)]);
  50404. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  50405. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  50406. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  50407. }
  50408. ++vertexCount;
  50409. });
  50410. }
  50411. }
  50412. var startingIndex = this._reconstructedMesh.getTotalIndices();
  50413. var startingVertex = this._reconstructedMesh.getTotalVertices();
  50414. var submeshesArray = this._reconstructedMesh.subMeshes;
  50415. this._reconstructedMesh.subMeshes = [];
  50416. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  50417. var originalIndices = this._mesh.getIndices();
  50418. for (i = 0; i < newTriangles.length; ++i) {
  50419. t = newTriangles[i]; //now get the new referencing point for each vertex
  50420. [0, 1, 2].forEach(function (idx) {
  50421. var id = originalIndices[t.originalOffset + idx];
  50422. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  50423. if (offset < 0)
  50424. offset = 0;
  50425. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  50426. });
  50427. }
  50428. //overwriting the old vertex buffers and indices.
  50429. this._reconstructedMesh.setIndices(newIndicesArray);
  50430. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  50431. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  50432. if (newUVsData.length > 0)
  50433. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  50434. if (newColorsData.length > 0)
  50435. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  50436. //create submesh
  50437. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  50438. if (submeshIndex > 0) {
  50439. this._reconstructedMesh.subMeshes = [];
  50440. submeshesArray.forEach(function (submesh) {
  50441. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  50442. });
  50443. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  50444. }
  50445. };
  50446. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  50447. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  50448. this._reconstructedMesh.material = this._mesh.material;
  50449. this._reconstructedMesh.parent = this._mesh.parent;
  50450. this._reconstructedMesh.isVisible = false;
  50451. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  50452. };
  50453. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  50454. for (var i = 0; i < vertex1.triangleCount; ++i) {
  50455. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  50456. if (t.deleted)
  50457. continue;
  50458. var s = this.references[vertex1.triangleStart + i].vertexId;
  50459. var v1 = t.vertices[(s + 1) % 3];
  50460. var v2 = t.vertices[(s + 2) % 3];
  50461. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  50462. deletedArray[i] = true;
  50463. delTr.push(t);
  50464. continue;
  50465. }
  50466. var d1 = v1.position.subtract(point);
  50467. d1 = d1.normalize();
  50468. var d2 = v2.position.subtract(point);
  50469. d2 = d2.normalize();
  50470. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  50471. return true;
  50472. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  50473. deletedArray[i] = false;
  50474. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  50475. return true;
  50476. }
  50477. return false;
  50478. };
  50479. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  50480. var newDeleted = deletedTriangles;
  50481. for (var i = 0; i < vertex.triangleCount; ++i) {
  50482. var ref = this.references[vertex.triangleStart + i];
  50483. var t = this.triangles[ref.triangleId];
  50484. if (t.deleted)
  50485. continue;
  50486. if (deletedArray[i] && t.deletePending) {
  50487. t.deleted = true;
  50488. newDeleted++;
  50489. continue;
  50490. }
  50491. t.vertices[ref.vertexId] = origVertex;
  50492. t.isDirty = true;
  50493. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  50494. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  50495. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  50496. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  50497. this.references.push(ref);
  50498. }
  50499. return newDeleted;
  50500. };
  50501. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  50502. for (var i = 0; i < this.vertices.length; ++i) {
  50503. var vCount = [];
  50504. var vId = [];
  50505. var v = this.vertices[i];
  50506. var j;
  50507. for (j = 0; j < v.triangleCount; ++j) {
  50508. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  50509. for (var ii = 0; ii < 3; ii++) {
  50510. var ofs = 0;
  50511. var vv = triangle.vertices[ii];
  50512. while (ofs < vCount.length) {
  50513. if (vId[ofs] === vv.id)
  50514. break;
  50515. ++ofs;
  50516. }
  50517. if (ofs === vCount.length) {
  50518. vCount.push(1);
  50519. vId.push(vv.id);
  50520. }
  50521. else {
  50522. vCount[ofs]++;
  50523. }
  50524. }
  50525. }
  50526. for (j = 0; j < vCount.length; ++j) {
  50527. if (vCount[j] === 1) {
  50528. this.vertices[vId[j]].isBorder = true;
  50529. }
  50530. else {
  50531. this.vertices[vId[j]].isBorder = false;
  50532. }
  50533. }
  50534. }
  50535. };
  50536. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  50537. if (identifyBorders === void 0) { identifyBorders = false; }
  50538. var i;
  50539. if (!identifyBorders) {
  50540. var newTrianglesVector = [];
  50541. for (i = 0; i < this.triangles.length; ++i) {
  50542. if (!this.triangles[i].deleted) {
  50543. newTrianglesVector.push(this.triangles[i]);
  50544. }
  50545. }
  50546. this.triangles = newTrianglesVector;
  50547. }
  50548. for (i = 0; i < this.vertices.length; ++i) {
  50549. this.vertices[i].triangleCount = 0;
  50550. this.vertices[i].triangleStart = 0;
  50551. }
  50552. var t;
  50553. var j;
  50554. var v;
  50555. for (i = 0; i < this.triangles.length; ++i) {
  50556. t = this.triangles[i];
  50557. for (j = 0; j < 3; ++j) {
  50558. v = t.vertices[j];
  50559. v.triangleCount++;
  50560. }
  50561. }
  50562. var tStart = 0;
  50563. for (i = 0; i < this.vertices.length; ++i) {
  50564. this.vertices[i].triangleStart = tStart;
  50565. tStart += this.vertices[i].triangleCount;
  50566. this.vertices[i].triangleCount = 0;
  50567. }
  50568. var newReferences = new Array(this.triangles.length * 3);
  50569. for (i = 0; i < this.triangles.length; ++i) {
  50570. t = this.triangles[i];
  50571. for (j = 0; j < 3; ++j) {
  50572. v = t.vertices[j];
  50573. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  50574. v.triangleCount++;
  50575. }
  50576. }
  50577. this.references = newReferences;
  50578. if (identifyBorders) {
  50579. this.identifyBorder();
  50580. }
  50581. };
  50582. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  50583. var x = point.x;
  50584. var y = point.y;
  50585. var z = point.z;
  50586. 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
  50587. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  50588. };
  50589. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  50590. var q = vertex1.q.add(vertex2.q);
  50591. var border = vertex1.isBorder && vertex2.isBorder;
  50592. var error = 0;
  50593. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  50594. if (qDet !== 0 && !border) {
  50595. if (!pointResult) {
  50596. pointResult = BABYLON.Vector3.Zero();
  50597. }
  50598. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  50599. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  50600. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  50601. error = this.vertexError(q, pointResult);
  50602. }
  50603. else {
  50604. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  50605. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  50606. var error1 = this.vertexError(q, vertex1.position);
  50607. var error2 = this.vertexError(q, vertex2.position);
  50608. var error3 = this.vertexError(q, p3);
  50609. error = Math.min(error1, error2, error3);
  50610. if (error === error1) {
  50611. if (pointResult) {
  50612. pointResult.copyFrom(vertex1.position);
  50613. }
  50614. }
  50615. else if (error === error2) {
  50616. if (pointResult) {
  50617. pointResult.copyFrom(vertex2.position);
  50618. }
  50619. }
  50620. else {
  50621. if (pointResult) {
  50622. pointResult.copyFrom(p3);
  50623. }
  50624. }
  50625. }
  50626. return error;
  50627. };
  50628. return QuadraticErrorSimplification;
  50629. }());
  50630. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  50631. })(BABYLON || (BABYLON = {}));
  50632. var BABYLON;
  50633. (function (BABYLON) {
  50634. var serializedGeometries = [];
  50635. var serializeGeometry = function (geometry, serializationGeometries) {
  50636. if (serializedGeometries[geometry.id]) {
  50637. return;
  50638. }
  50639. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  50640. serializationGeometries.boxes.push(geometry.serialize());
  50641. }
  50642. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  50643. serializationGeometries.spheres.push(geometry.serialize());
  50644. }
  50645. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  50646. serializationGeometries.cylinders.push(geometry.serialize());
  50647. }
  50648. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  50649. serializationGeometries.toruses.push(geometry.serialize());
  50650. }
  50651. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  50652. serializationGeometries.grounds.push(geometry.serialize());
  50653. }
  50654. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  50655. serializationGeometries.planes.push(geometry.serialize());
  50656. }
  50657. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  50658. serializationGeometries.torusKnots.push(geometry.serialize());
  50659. }
  50660. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  50661. throw new Error("Unknown primitive type");
  50662. }
  50663. else {
  50664. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  50665. }
  50666. serializedGeometries[geometry.id] = true;
  50667. };
  50668. var serializeMesh = function (mesh, serializationScene) {
  50669. var serializationObject = {};
  50670. serializationObject.name = mesh.name;
  50671. serializationObject.id = mesh.id;
  50672. if (BABYLON.Tags.HasTags(mesh)) {
  50673. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  50674. }
  50675. serializationObject.position = mesh.position.asArray();
  50676. if (mesh.rotationQuaternion) {
  50677. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  50678. }
  50679. else if (mesh.rotation) {
  50680. serializationObject.rotation = mesh.rotation.asArray();
  50681. }
  50682. serializationObject.scaling = mesh.scaling.asArray();
  50683. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  50684. serializationObject.isEnabled = mesh.isEnabled();
  50685. serializationObject.isVisible = mesh.isVisible;
  50686. serializationObject.infiniteDistance = mesh.infiniteDistance;
  50687. serializationObject.pickable = mesh.isPickable;
  50688. serializationObject.receiveShadows = mesh.receiveShadows;
  50689. serializationObject.billboardMode = mesh.billboardMode;
  50690. serializationObject.visibility = mesh.visibility;
  50691. serializationObject.checkCollisions = mesh.checkCollisions;
  50692. // Parent
  50693. if (mesh.parent) {
  50694. serializationObject.parentId = mesh.parent.id;
  50695. }
  50696. // Geometry
  50697. var geometry = mesh._geometry;
  50698. if (geometry) {
  50699. var geometryId = geometry.id;
  50700. serializationObject.geometryId = geometryId;
  50701. if (!mesh.getScene().getGeometryByID(geometryId)) {
  50702. // 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
  50703. serializeGeometry(geometry, serializationScene.geometries);
  50704. }
  50705. // SubMeshes
  50706. serializationObject.subMeshes = [];
  50707. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  50708. var subMesh = mesh.subMeshes[subIndex];
  50709. serializationObject.subMeshes.push({
  50710. materialIndex: subMesh.materialIndex,
  50711. verticesStart: subMesh.verticesStart,
  50712. verticesCount: subMesh.verticesCount,
  50713. indexStart: subMesh.indexStart,
  50714. indexCount: subMesh.indexCount
  50715. });
  50716. }
  50717. }
  50718. // Material
  50719. if (mesh.material) {
  50720. serializationObject.materialId = mesh.material.id;
  50721. }
  50722. else {
  50723. mesh.material = null;
  50724. }
  50725. // Skeleton
  50726. if (mesh.skeleton) {
  50727. serializationObject.skeletonId = mesh.skeleton.id;
  50728. }
  50729. // Physics
  50730. //TODO implement correct serialization for physics impostors.
  50731. if (mesh.getPhysicsImpostor()) {
  50732. serializationObject.physicsMass = mesh.getPhysicsMass();
  50733. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  50734. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  50735. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  50736. }
  50737. // Instances
  50738. serializationObject.instances = [];
  50739. for (var index = 0; index < mesh.instances.length; index++) {
  50740. var instance = mesh.instances[index];
  50741. var serializationInstance = {
  50742. name: instance.name,
  50743. position: instance.position.asArray(),
  50744. scaling: instance.scaling.asArray()
  50745. };
  50746. if (instance.rotationQuaternion) {
  50747. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  50748. }
  50749. else if (instance.rotation) {
  50750. serializationInstance.rotation = instance.rotation.asArray();
  50751. }
  50752. serializationObject.instances.push(serializationInstance);
  50753. // Animations
  50754. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  50755. serializationInstance.ranges = instance.serializeAnimationRanges();
  50756. }
  50757. // Animations
  50758. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  50759. serializationObject.ranges = mesh.serializeAnimationRanges();
  50760. // Layer mask
  50761. serializationObject.layerMask = mesh.layerMask;
  50762. // Action Manager
  50763. if (mesh.actionManager) {
  50764. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  50765. }
  50766. return serializationObject;
  50767. };
  50768. var finalizeSingleMesh = function (mesh, serializationObject) {
  50769. //only works if the mesh is already loaded
  50770. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  50771. //serialize material
  50772. if (mesh.material) {
  50773. if (mesh.material instanceof BABYLON.StandardMaterial) {
  50774. serializationObject.materials = serializationObject.materials || [];
  50775. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  50776. serializationObject.materials.push(mesh.material.serialize());
  50777. }
  50778. }
  50779. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  50780. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  50781. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  50782. serializationObject.multiMaterials.push(mesh.material.serialize());
  50783. }
  50784. }
  50785. }
  50786. //serialize geometry
  50787. var geometry = mesh._geometry;
  50788. if (geometry) {
  50789. if (!serializationObject.geometries) {
  50790. serializationObject.geometries = {};
  50791. serializationObject.geometries.boxes = [];
  50792. serializationObject.geometries.spheres = [];
  50793. serializationObject.geometries.cylinders = [];
  50794. serializationObject.geometries.toruses = [];
  50795. serializationObject.geometries.grounds = [];
  50796. serializationObject.geometries.planes = [];
  50797. serializationObject.geometries.torusKnots = [];
  50798. serializationObject.geometries.vertexData = [];
  50799. }
  50800. serializeGeometry(geometry, serializationObject.geometries);
  50801. }
  50802. // Skeletons
  50803. if (mesh.skeleton) {
  50804. serializationObject.skeletons = serializationObject.skeletons || [];
  50805. serializationObject.skeletons.push(mesh.skeleton.serialize());
  50806. }
  50807. //serialize the actual mesh
  50808. serializationObject.meshes = serializationObject.meshes || [];
  50809. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  50810. }
  50811. };
  50812. var SceneSerializer = (function () {
  50813. function SceneSerializer() {
  50814. }
  50815. SceneSerializer.ClearCache = function () {
  50816. serializedGeometries = [];
  50817. };
  50818. SceneSerializer.Serialize = function (scene) {
  50819. var serializationObject = {};
  50820. // Scene
  50821. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  50822. serializationObject.autoClear = scene.autoClear;
  50823. serializationObject.clearColor = scene.clearColor.asArray();
  50824. serializationObject.ambientColor = scene.ambientColor.asArray();
  50825. serializationObject.gravity = scene.gravity.asArray();
  50826. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  50827. serializationObject.workerCollisions = scene.workerCollisions;
  50828. // Fog
  50829. if (scene.fogMode && scene.fogMode !== 0) {
  50830. serializationObject.fogMode = scene.fogMode;
  50831. serializationObject.fogColor = scene.fogColor.asArray();
  50832. serializationObject.fogStart = scene.fogStart;
  50833. serializationObject.fogEnd = scene.fogEnd;
  50834. serializationObject.fogDensity = scene.fogDensity;
  50835. }
  50836. //Physics
  50837. if (scene.isPhysicsEnabled()) {
  50838. serializationObject.physicsEnabled = true;
  50839. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  50840. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  50841. }
  50842. // Lights
  50843. serializationObject.lights = [];
  50844. var index;
  50845. var light;
  50846. for (index = 0; index < scene.lights.length; index++) {
  50847. light = scene.lights[index];
  50848. serializationObject.lights.push(light.serialize());
  50849. }
  50850. // Cameras
  50851. serializationObject.cameras = [];
  50852. for (index = 0; index < scene.cameras.length; index++) {
  50853. var camera = scene.cameras[index];
  50854. serializationObject.cameras.push(camera.serialize());
  50855. }
  50856. if (scene.activeCamera) {
  50857. serializationObject.activeCameraID = scene.activeCamera.id;
  50858. }
  50859. // Animations
  50860. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  50861. // Materials
  50862. serializationObject.materials = [];
  50863. serializationObject.multiMaterials = [];
  50864. var material;
  50865. for (index = 0; index < scene.materials.length; index++) {
  50866. material = scene.materials[index];
  50867. serializationObject.materials.push(material.serialize());
  50868. }
  50869. // MultiMaterials
  50870. serializationObject.multiMaterials = [];
  50871. for (index = 0; index < scene.multiMaterials.length; index++) {
  50872. var multiMaterial = scene.multiMaterials[index];
  50873. serializationObject.multiMaterials.push(multiMaterial.serialize());
  50874. }
  50875. // Skeletons
  50876. serializationObject.skeletons = [];
  50877. for (index = 0; index < scene.skeletons.length; index++) {
  50878. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  50879. }
  50880. // Geometries
  50881. serializationObject.geometries = {};
  50882. serializationObject.geometries.boxes = [];
  50883. serializationObject.geometries.spheres = [];
  50884. serializationObject.geometries.cylinders = [];
  50885. serializationObject.geometries.toruses = [];
  50886. serializationObject.geometries.grounds = [];
  50887. serializationObject.geometries.planes = [];
  50888. serializationObject.geometries.torusKnots = [];
  50889. serializationObject.geometries.vertexData = [];
  50890. serializedGeometries = [];
  50891. var geometries = scene.getGeometries();
  50892. for (index = 0; index < geometries.length; index++) {
  50893. var geometry = geometries[index];
  50894. if (geometry.isReady()) {
  50895. serializeGeometry(geometry, serializationObject.geometries);
  50896. }
  50897. }
  50898. // Meshes
  50899. serializationObject.meshes = [];
  50900. for (index = 0; index < scene.meshes.length; index++) {
  50901. var abstractMesh = scene.meshes[index];
  50902. if (abstractMesh instanceof BABYLON.Mesh) {
  50903. var mesh = abstractMesh;
  50904. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  50905. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  50906. }
  50907. }
  50908. }
  50909. // Particles Systems
  50910. serializationObject.particleSystems = [];
  50911. for (index = 0; index < scene.particleSystems.length; index++) {
  50912. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  50913. }
  50914. // Lens flares
  50915. serializationObject.lensFlareSystems = [];
  50916. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  50917. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  50918. }
  50919. // Shadows
  50920. serializationObject.shadowGenerators = [];
  50921. for (index = 0; index < scene.lights.length; index++) {
  50922. light = scene.lights[index];
  50923. var shadowGenerator = light.getShadowGenerator();
  50924. // Only support serialization for official generator so far.
  50925. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  50926. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  50927. }
  50928. }
  50929. // Action Manager
  50930. if (scene.actionManager) {
  50931. serializationObject.actions = scene.actionManager.serialize("scene");
  50932. }
  50933. // Audio
  50934. serializationObject.sounds = [];
  50935. for (index = 0; index < scene.soundTracks.length; index++) {
  50936. var soundtrack = scene.soundTracks[index];
  50937. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  50938. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  50939. }
  50940. }
  50941. return serializationObject;
  50942. };
  50943. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  50944. if (withParents === void 0) { withParents = false; }
  50945. if (withChildren === void 0) { withChildren = false; }
  50946. var serializationObject = {};
  50947. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  50948. if (withParents || withChildren) {
  50949. //deliberate for loop! not for each, appended should be processed as well.
  50950. for (var i = 0; i < toSerialize.length; ++i) {
  50951. if (withChildren) {
  50952. toSerialize[i].getDescendants().forEach(function (node) {
  50953. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  50954. toSerialize.push(node);
  50955. }
  50956. });
  50957. }
  50958. //make sure the array doesn't contain the object already
  50959. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  50960. toSerialize.push(toSerialize[i].parent);
  50961. }
  50962. }
  50963. }
  50964. toSerialize.forEach(function (mesh) {
  50965. finalizeSingleMesh(mesh, serializationObject);
  50966. });
  50967. return serializationObject;
  50968. };
  50969. return SceneSerializer;
  50970. }());
  50971. BABYLON.SceneSerializer = SceneSerializer;
  50972. })(BABYLON || (BABYLON = {}));
  50973. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  50974. // Huge respect for a such great lib.
  50975. // Earcut license:
  50976. // Copyright (c) 2016, Mapbox
  50977. //
  50978. // Permission to use, copy, modify, and/or distribute this software for any purpose
  50979. // with or without fee is hereby granted, provided that the above copyright notice
  50980. // and this permission notice appear in all copies.
  50981. //
  50982. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  50983. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  50984. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  50985. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  50986. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  50987. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  50988. // THIS SOFTWARE.
  50989. var Earcut;
  50990. (function (Earcut) {
  50991. /**
  50992. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  50993. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  50994. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  50995. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  50996. */
  50997. function earcut(data, holeIndices, dim) {
  50998. dim = dim || 2;
  50999. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  51000. if (!outerNode)
  51001. return triangles;
  51002. var minX, minY, maxX, maxY, x, y, size;
  51003. if (hasHoles)
  51004. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  51005. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  51006. if (data.length > 80 * dim) {
  51007. minX = maxX = data[0];
  51008. minY = maxY = data[1];
  51009. for (var i = dim; i < outerLen; i += dim) {
  51010. x = data[i];
  51011. y = data[i + 1];
  51012. if (x < minX)
  51013. minX = x;
  51014. if (y < minY)
  51015. minY = y;
  51016. if (x > maxX)
  51017. maxX = x;
  51018. if (y > maxY)
  51019. maxY = y;
  51020. }
  51021. // minX, minY and size are later used to transform coords into integers for z-order calculation
  51022. size = Math.max(maxX - minX, maxY - minY);
  51023. }
  51024. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  51025. return triangles;
  51026. }
  51027. Earcut.earcut = earcut;
  51028. // create a circular doubly linked list from polygon points in the specified winding order
  51029. function linkedList(data, start, end, dim, clockwise) {
  51030. var i, last;
  51031. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  51032. for (i = start; i < end; i += dim)
  51033. last = insertNode(i, data[i], data[i + 1], last);
  51034. }
  51035. else {
  51036. for (i = end - dim; i >= start; i -= dim)
  51037. last = insertNode(i, data[i], data[i + 1], last);
  51038. }
  51039. if (last && equals(last, last.next)) {
  51040. removeNode(last);
  51041. last = last.next;
  51042. }
  51043. return last;
  51044. }
  51045. // eliminate colinear or duplicate points
  51046. function filterPoints(start, end) {
  51047. if (!start)
  51048. return start;
  51049. if (!end)
  51050. end = start;
  51051. var p = start, again;
  51052. do {
  51053. again = false;
  51054. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  51055. removeNode(p);
  51056. p = end = p.prev;
  51057. if (p === p.next)
  51058. return null;
  51059. again = true;
  51060. }
  51061. else {
  51062. p = p.next;
  51063. }
  51064. } while (again || p !== end);
  51065. return end;
  51066. }
  51067. // main ear slicing loop which triangulates a polygon (given as a linked list)
  51068. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  51069. if (!ear)
  51070. return;
  51071. // interlink polygon nodes in z-order
  51072. if (!pass && size)
  51073. indexCurve(ear, minX, minY, size);
  51074. var stop = ear, prev, next;
  51075. // iterate through ears, slicing them one by one
  51076. while (ear.prev !== ear.next) {
  51077. prev = ear.prev;
  51078. next = ear.next;
  51079. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  51080. // cut off the triangle
  51081. triangles.push(prev.i / dim);
  51082. triangles.push(ear.i / dim);
  51083. triangles.push(next.i / dim);
  51084. removeNode(ear);
  51085. // skipping the next vertice leads to less sliver triangles
  51086. ear = next.next;
  51087. stop = next.next;
  51088. continue;
  51089. }
  51090. ear = next;
  51091. // if we looped through the whole remaining polygon and can't find any more ears
  51092. if (ear === stop) {
  51093. // try filtering points and slicing again
  51094. if (!pass) {
  51095. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  51096. }
  51097. else if (pass === 1) {
  51098. ear = cureLocalIntersections(ear, triangles, dim);
  51099. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  51100. }
  51101. else if (pass === 2) {
  51102. splitEarcut(ear, triangles, dim, minX, minY, size);
  51103. }
  51104. break;
  51105. }
  51106. }
  51107. }
  51108. // check whether a polygon node forms a valid ear with adjacent nodes
  51109. function isEar(ear) {
  51110. var a = ear.prev, b = ear, c = ear.next;
  51111. if (area(a, b, c) >= 0)
  51112. return false; // reflex, can't be an ear
  51113. // now make sure we don't have other points inside the potential ear
  51114. var p = ear.next.next;
  51115. while (p !== ear.prev) {
  51116. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51117. area(p.prev, p, p.next) >= 0)
  51118. return false;
  51119. p = p.next;
  51120. }
  51121. return true;
  51122. }
  51123. function isEarHashed(ear, minX, minY, size) {
  51124. var a = ear.prev, b = ear, c = ear.next;
  51125. if (area(a, b, c) >= 0)
  51126. return false; // reflex, can't be an ear
  51127. // triangle bbox; min & max are calculated like this for speed
  51128. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  51129. // z-order range for the current triangle bbox;
  51130. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  51131. // first look for points inside the triangle in increasing z-order
  51132. var p = ear.nextZ;
  51133. while (p && p.z <= maxZ) {
  51134. if (p !== ear.prev &&
  51135. p !== ear.next &&
  51136. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51137. area(p.prev, p, p.next) >= 0)
  51138. return false;
  51139. p = p.nextZ;
  51140. }
  51141. // then look for points in decreasing z-order
  51142. p = ear.prevZ;
  51143. while (p && p.z >= minZ) {
  51144. if (p !== ear.prev &&
  51145. p !== ear.next &&
  51146. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  51147. area(p.prev, p, p.next) >= 0)
  51148. return false;
  51149. p = p.prevZ;
  51150. }
  51151. return true;
  51152. }
  51153. // go through all polygon nodes and cure small local self-intersections
  51154. function cureLocalIntersections(start, triangles, dim) {
  51155. var p = start;
  51156. do {
  51157. var a = p.prev, b = p.next.next;
  51158. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  51159. triangles.push(a.i / dim);
  51160. triangles.push(p.i / dim);
  51161. triangles.push(b.i / dim);
  51162. // remove two nodes involved
  51163. removeNode(p);
  51164. removeNode(p.next);
  51165. p = start = b;
  51166. }
  51167. p = p.next;
  51168. } while (p !== start);
  51169. return p;
  51170. }
  51171. // try splitting polygon into two and triangulate them independently
  51172. function splitEarcut(start, triangles, dim, minX, minY, size) {
  51173. // look for a valid diagonal that divides the polygon into two
  51174. var a = start;
  51175. do {
  51176. var b = a.next.next;
  51177. while (b !== a.prev) {
  51178. if (a.i !== b.i && isValidDiagonal(a, b)) {
  51179. // split the polygon in two by the diagonal
  51180. var c = splitPolygon(a, b);
  51181. // filter colinear points around the cuts
  51182. a = filterPoints(a, a.next);
  51183. c = filterPoints(c, c.next);
  51184. // run earcut on each half
  51185. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  51186. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  51187. return;
  51188. }
  51189. b = b.next;
  51190. }
  51191. a = a.next;
  51192. } while (a !== start);
  51193. }
  51194. // link every hole into the outer loop, producing a single-ring polygon without holes
  51195. function eliminateHoles(data, holeIndices, outerNode, dim) {
  51196. var queue = [], i, len, start, end, list;
  51197. for (i = 0, len = holeIndices.length; i < len; i++) {
  51198. start = holeIndices[i] * dim;
  51199. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  51200. list = linkedList(data, start, end, dim, false);
  51201. if (list === list.next)
  51202. list.steiner = true;
  51203. queue.push(getLeftmost(list));
  51204. }
  51205. queue.sort(compareX);
  51206. // process holes from left to right
  51207. for (i = 0; i < queue.length; i++) {
  51208. eliminateHole(queue[i], outerNode);
  51209. outerNode = filterPoints(outerNode, outerNode.next);
  51210. }
  51211. return outerNode;
  51212. }
  51213. function compareX(a, b) {
  51214. return a.x - b.x;
  51215. }
  51216. // find a bridge between vertices that connects hole with an outer ring and and link it
  51217. function eliminateHole(hole, outerNode) {
  51218. outerNode = findHoleBridge(hole, outerNode);
  51219. if (outerNode) {
  51220. var b = splitPolygon(outerNode, hole);
  51221. filterPoints(b, b.next);
  51222. }
  51223. }
  51224. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  51225. function findHoleBridge(hole, outerNode) {
  51226. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  51227. // find a segment intersected by a ray from the hole's leftmost point to the left;
  51228. // segment's endpoint with lesser x will be potential connection point
  51229. do {
  51230. if (hy <= p.y && hy >= p.next.y) {
  51231. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  51232. if (x <= hx && x > qx) {
  51233. qx = x;
  51234. if (x === hx) {
  51235. if (hy === p.y)
  51236. return p;
  51237. if (hy === p.next.y)
  51238. return p.next;
  51239. }
  51240. m = p.x < p.next.x ? p : p.next;
  51241. }
  51242. }
  51243. p = p.next;
  51244. } while (p !== outerNode);
  51245. if (!m)
  51246. return null;
  51247. if (hx === qx)
  51248. return m.prev; // hole touches outer segment; pick lower endpoint
  51249. // look for points inside the triangle of hole point, segment intersection and endpoint;
  51250. // if there are no points found, we have a valid connection;
  51251. // otherwise choose the point of the minimum angle with the ray as connection point
  51252. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  51253. p = m.next;
  51254. while (p !== stop) {
  51255. if (hx >= p.x &&
  51256. p.x >= mx &&
  51257. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  51258. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  51259. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  51260. m = p;
  51261. tanMin = tan;
  51262. }
  51263. }
  51264. p = p.next;
  51265. }
  51266. return m;
  51267. }
  51268. // interlink polygon nodes in z-order
  51269. function indexCurve(start, minX, minY, size) {
  51270. var p = start;
  51271. do {
  51272. if (p.z === null)
  51273. p.z = zOrder(p.x, p.y, minX, minY, size);
  51274. p.prevZ = p.prev;
  51275. p.nextZ = p.next;
  51276. p = p.next;
  51277. } while (p !== start);
  51278. p.prevZ.nextZ = null;
  51279. p.prevZ = null;
  51280. sortLinked(p);
  51281. }
  51282. // Simon Tatham's linked list merge sort algorithm
  51283. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  51284. function sortLinked(list) {
  51285. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  51286. do {
  51287. p = list;
  51288. list = null;
  51289. tail = null;
  51290. numMerges = 0;
  51291. while (p) {
  51292. numMerges++;
  51293. q = p;
  51294. pSize = 0;
  51295. for (i = 0; i < inSize; i++) {
  51296. pSize++;
  51297. q = q.nextZ;
  51298. if (!q)
  51299. break;
  51300. }
  51301. qSize = inSize;
  51302. while (pSize > 0 || (qSize > 0 && q)) {
  51303. if (pSize === 0) {
  51304. e = q;
  51305. q = q.nextZ;
  51306. qSize--;
  51307. }
  51308. else if (qSize === 0 || !q) {
  51309. e = p;
  51310. p = p.nextZ;
  51311. pSize--;
  51312. }
  51313. else if (p.z <= q.z) {
  51314. e = p;
  51315. p = p.nextZ;
  51316. pSize--;
  51317. }
  51318. else {
  51319. e = q;
  51320. q = q.nextZ;
  51321. qSize--;
  51322. }
  51323. if (tail)
  51324. tail.nextZ = e;
  51325. else
  51326. list = e;
  51327. e.prevZ = tail;
  51328. tail = e;
  51329. }
  51330. p = q;
  51331. }
  51332. tail.nextZ = null;
  51333. inSize *= 2;
  51334. } while (numMerges > 1);
  51335. return list;
  51336. }
  51337. // z-order of a point given coords and size of the data bounding box
  51338. function zOrder(x, y, minX, minY, size) {
  51339. // coords are transformed into non-negative 15-bit integer range
  51340. x = 32767 * (x - minX) / size;
  51341. y = 32767 * (y - minY) / size;
  51342. x = (x | (x << 8)) & 0x00FF00FF;
  51343. x = (x | (x << 4)) & 0x0F0F0F0F;
  51344. x = (x | (x << 2)) & 0x33333333;
  51345. x = (x | (x << 1)) & 0x55555555;
  51346. y = (y | (y << 8)) & 0x00FF00FF;
  51347. y = (y | (y << 4)) & 0x0F0F0F0F;
  51348. y = (y | (y << 2)) & 0x33333333;
  51349. y = (y | (y << 1)) & 0x55555555;
  51350. return x | (y << 1);
  51351. }
  51352. // find the leftmost node of a polygon ring
  51353. function getLeftmost(start) {
  51354. var p = start, leftmost = start;
  51355. do {
  51356. if (p.x < leftmost.x)
  51357. leftmost = p;
  51358. p = p.next;
  51359. } while (p !== start);
  51360. return leftmost;
  51361. }
  51362. // check if a point lies within a convex triangle
  51363. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  51364. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  51365. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  51366. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  51367. }
  51368. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  51369. function isValidDiagonal(a, b) {
  51370. return a.next.i !== b.i &&
  51371. a.prev.i !== b.i &&
  51372. !intersectsPolygon(a, b) &&
  51373. locallyInside(a, b) &&
  51374. locallyInside(b, a) &&
  51375. middleInside(a, b);
  51376. }
  51377. // signed area of a triangle
  51378. function area(p, q, r) {
  51379. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  51380. }
  51381. // check if two points are equal
  51382. function equals(p1, p2) {
  51383. return p1.x === p2.x && p1.y === p2.y;
  51384. }
  51385. // check if two segments intersect
  51386. function intersects(p1, q1, p2, q2) {
  51387. if ((equals(p1, q1) && equals(p2, q2)) ||
  51388. (equals(p1, q2) && equals(p2, q1)))
  51389. return true;
  51390. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  51391. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  51392. }
  51393. // check if a polygon diagonal intersects any polygon segments
  51394. function intersectsPolygon(a, b) {
  51395. var p = a;
  51396. do {
  51397. if (p.i !== a.i &&
  51398. p.next.i !== a.i &&
  51399. p.i !== b.i &&
  51400. p.next.i !== b.i &&
  51401. intersects(p, p.next, a, b))
  51402. return true;
  51403. p = p.next;
  51404. } while (p !== a);
  51405. return false;
  51406. }
  51407. // check if a polygon diagonal is locally inside the polygon
  51408. function locallyInside(a, b) {
  51409. return area(a.prev, a, a.next) < 0
  51410. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  51411. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  51412. }
  51413. // check if the middle point of a polygon diagonal is inside the polygon
  51414. function middleInside(a, b) {
  51415. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  51416. do {
  51417. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  51418. inside = !inside;
  51419. p = p.next;
  51420. } while (p !== a);
  51421. return inside;
  51422. }
  51423. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  51424. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  51425. function splitPolygon(a, b) {
  51426. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  51427. a.next = b;
  51428. b.prev = a;
  51429. a2.next = an;
  51430. an.prev = a2;
  51431. b2.next = a2;
  51432. a2.prev = b2;
  51433. bp.next = b2;
  51434. b2.prev = bp;
  51435. return b2;
  51436. }
  51437. // create a node and optionally link it with previous one (in a circular doubly linked list)
  51438. function insertNode(i, x, y, last) {
  51439. var p = new Node(i, x, y);
  51440. if (!last) {
  51441. p.prev = p;
  51442. p.next = p;
  51443. }
  51444. else {
  51445. p.next = last.next;
  51446. p.prev = last;
  51447. last.next.prev = p;
  51448. last.next = p;
  51449. }
  51450. return p;
  51451. }
  51452. function removeNode(p) {
  51453. p.next.prev = p.prev;
  51454. p.prev.next = p.next;
  51455. if (p.prevZ)
  51456. p.prevZ.nextZ = p.nextZ;
  51457. if (p.nextZ)
  51458. p.nextZ.prevZ = p.prevZ;
  51459. }
  51460. function Node(i, x, y) {
  51461. // vertice index in coordinates array
  51462. this.i = i;
  51463. // vertex coordinates
  51464. this.x = x;
  51465. this.y = y;
  51466. // previous and next vertice nodes in a polygon ring
  51467. this.prev = null;
  51468. this.next = null;
  51469. // z-order curve value
  51470. this.z = null;
  51471. // previous and next nodes in z-order
  51472. this.prevZ = null;
  51473. this.nextZ = null;
  51474. // indicates whether this is a steiner point
  51475. this.steiner = false;
  51476. }
  51477. /**
  51478. * return a percentage difference between the polygon area and its triangulation area;
  51479. * used to verify correctness of triangulation
  51480. */
  51481. function deviation(data, holeIndices, dim, triangles) {
  51482. var hasHoles = holeIndices && holeIndices.length;
  51483. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  51484. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  51485. if (hasHoles) {
  51486. for (var i = 0, len = holeIndices.length; i < len; i++) {
  51487. var start = holeIndices[i] * dim;
  51488. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  51489. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  51490. }
  51491. }
  51492. var trianglesArea = 0;
  51493. for (i = 0; i < triangles.length; i += 3) {
  51494. var a = triangles[i] * dim;
  51495. var b = triangles[i + 1] * dim;
  51496. var c = triangles[i + 2] * dim;
  51497. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  51498. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  51499. }
  51500. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  51501. }
  51502. Earcut.deviation = deviation;
  51503. ;
  51504. function signedArea(data, start, end, dim) {
  51505. var sum = 0;
  51506. for (var i = start, j = end - dim; i < end; i += dim) {
  51507. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  51508. j = i;
  51509. }
  51510. return sum;
  51511. }
  51512. /**
  51513. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  51514. */
  51515. function flatten(data) {
  51516. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  51517. for (var i = 0; i < data.length; i++) {
  51518. for (var j = 0; j < data[i].length; j++) {
  51519. for (var d = 0; d < dim; d++)
  51520. result.vertices.push(data[i][j][d]);
  51521. }
  51522. if (i > 0) {
  51523. holeIndex += data[i - 1].length;
  51524. result.holes.push(holeIndex);
  51525. }
  51526. }
  51527. return result;
  51528. }
  51529. Earcut.flatten = flatten;
  51530. ;
  51531. })(Earcut || (Earcut = {}));
  51532. var BABYLON;
  51533. (function (BABYLON) {
  51534. // Unique ID when we import meshes from Babylon to CSG
  51535. var currentCSGMeshId = 0;
  51536. // # class Vertex
  51537. // Represents a vertex of a polygon. Use your own vertex class instead of this
  51538. // one to provide additional features like texture coordinates and vertex
  51539. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  51540. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  51541. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  51542. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  51543. // is not used anywhere else.
  51544. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  51545. var Vertex = (function () {
  51546. function Vertex(pos, normal, uv) {
  51547. this.pos = pos;
  51548. this.normal = normal;
  51549. this.uv = uv;
  51550. }
  51551. Vertex.prototype.clone = function () {
  51552. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  51553. };
  51554. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  51555. // orientation of a polygon is flipped.
  51556. Vertex.prototype.flip = function () {
  51557. this.normal = this.normal.scale(-1);
  51558. };
  51559. // Create a new vertex between this vertex and `other` by linearly
  51560. // interpolating all properties using a parameter of `t`. Subclasses should
  51561. // override this to interpolate additional properties.
  51562. Vertex.prototype.interpolate = function (other, t) {
  51563. 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));
  51564. };
  51565. return Vertex;
  51566. }());
  51567. // # class Plane
  51568. // Represents a plane in 3D space.
  51569. var Plane = (function () {
  51570. function Plane(normal, w) {
  51571. this.normal = normal;
  51572. this.w = w;
  51573. }
  51574. Plane.FromPoints = function (a, b, c) {
  51575. var v0 = c.subtract(a);
  51576. var v1 = b.subtract(a);
  51577. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  51578. return null;
  51579. }
  51580. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  51581. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  51582. };
  51583. Plane.prototype.clone = function () {
  51584. return new Plane(this.normal.clone(), this.w);
  51585. };
  51586. Plane.prototype.flip = function () {
  51587. this.normal.scaleInPlace(-1);
  51588. this.w = -this.w;
  51589. };
  51590. // Split `polygon` by this plane if needed, then put the polygon or polygon
  51591. // fragments in the appropriate lists. Coplanar polygons go into either
  51592. // `coplanarFront` or `coplanarBack` depending on their orientation with
  51593. // respect to this plane. Polygons in front or in back of this plane go into
  51594. // either `front` or `back`.
  51595. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  51596. var COPLANAR = 0;
  51597. var FRONT = 1;
  51598. var BACK = 2;
  51599. var SPANNING = 3;
  51600. // Classify each point as well as the entire polygon into one of the above
  51601. // four classes.
  51602. var polygonType = 0;
  51603. var types = [];
  51604. var i;
  51605. var t;
  51606. for (i = 0; i < polygon.vertices.length; i++) {
  51607. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  51608. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  51609. polygonType |= type;
  51610. types.push(type);
  51611. }
  51612. // Put the polygon in the correct list, splitting it when necessary.
  51613. switch (polygonType) {
  51614. case COPLANAR:
  51615. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  51616. break;
  51617. case FRONT:
  51618. front.push(polygon);
  51619. break;
  51620. case BACK:
  51621. back.push(polygon);
  51622. break;
  51623. case SPANNING:
  51624. var f = [], b = [];
  51625. for (i = 0; i < polygon.vertices.length; i++) {
  51626. var j = (i + 1) % polygon.vertices.length;
  51627. var ti = types[i], tj = types[j];
  51628. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  51629. if (ti !== BACK)
  51630. f.push(vi);
  51631. if (ti !== FRONT)
  51632. b.push(ti !== BACK ? vi.clone() : vi);
  51633. if ((ti | tj) === SPANNING) {
  51634. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  51635. var v = vi.interpolate(vj, t);
  51636. f.push(v);
  51637. b.push(v.clone());
  51638. }
  51639. }
  51640. var poly;
  51641. if (f.length >= 3) {
  51642. poly = new Polygon(f, polygon.shared);
  51643. if (poly.plane)
  51644. front.push(poly);
  51645. }
  51646. if (b.length >= 3) {
  51647. poly = new Polygon(b, polygon.shared);
  51648. if (poly.plane)
  51649. back.push(poly);
  51650. }
  51651. break;
  51652. }
  51653. };
  51654. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  51655. // point is on the plane.
  51656. Plane.EPSILON = 1e-5;
  51657. return Plane;
  51658. }());
  51659. // # class Polygon
  51660. // Represents a convex polygon. The vertices used to initialize a polygon must
  51661. // be coplanar and form a convex loop.
  51662. //
  51663. // Each convex polygon has a `shared` property, which is shared between all
  51664. // polygons that are clones of each other or were split from the same polygon.
  51665. // This can be used to define per-polygon properties (such as surface color).
  51666. var Polygon = (function () {
  51667. function Polygon(vertices, shared) {
  51668. this.vertices = vertices;
  51669. this.shared = shared;
  51670. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  51671. }
  51672. Polygon.prototype.clone = function () {
  51673. var vertices = this.vertices.map(function (v) { return v.clone(); });
  51674. return new Polygon(vertices, this.shared);
  51675. };
  51676. Polygon.prototype.flip = function () {
  51677. this.vertices.reverse().map(function (v) { v.flip(); });
  51678. this.plane.flip();
  51679. };
  51680. return Polygon;
  51681. }());
  51682. // # class Node
  51683. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  51684. // by picking a polygon to split along. That polygon (and all other coplanar
  51685. // polygons) are added directly to that node and the other polygons are added to
  51686. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  51687. // no distinction between internal and leaf nodes.
  51688. var Node = (function () {
  51689. function Node(polygons) {
  51690. this.plane = null;
  51691. this.front = null;
  51692. this.back = null;
  51693. this.polygons = [];
  51694. if (polygons) {
  51695. this.build(polygons);
  51696. }
  51697. }
  51698. Node.prototype.clone = function () {
  51699. var node = new Node();
  51700. node.plane = this.plane && this.plane.clone();
  51701. node.front = this.front && this.front.clone();
  51702. node.back = this.back && this.back.clone();
  51703. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  51704. return node;
  51705. };
  51706. // Convert solid space to empty space and empty space to solid space.
  51707. Node.prototype.invert = function () {
  51708. for (var i = 0; i < this.polygons.length; i++) {
  51709. this.polygons[i].flip();
  51710. }
  51711. if (this.plane) {
  51712. this.plane.flip();
  51713. }
  51714. if (this.front) {
  51715. this.front.invert();
  51716. }
  51717. if (this.back) {
  51718. this.back.invert();
  51719. }
  51720. var temp = this.front;
  51721. this.front = this.back;
  51722. this.back = temp;
  51723. };
  51724. // Recursively remove all polygons in `polygons` that are inside this BSP
  51725. // tree.
  51726. Node.prototype.clipPolygons = function (polygons) {
  51727. if (!this.plane)
  51728. return polygons.slice();
  51729. var front = [], back = [];
  51730. for (var i = 0; i < polygons.length; i++) {
  51731. this.plane.splitPolygon(polygons[i], front, back, front, back);
  51732. }
  51733. if (this.front) {
  51734. front = this.front.clipPolygons(front);
  51735. }
  51736. if (this.back) {
  51737. back = this.back.clipPolygons(back);
  51738. }
  51739. else {
  51740. back = [];
  51741. }
  51742. return front.concat(back);
  51743. };
  51744. // Remove all polygons in this BSP tree that are inside the other BSP tree
  51745. // `bsp`.
  51746. Node.prototype.clipTo = function (bsp) {
  51747. this.polygons = bsp.clipPolygons(this.polygons);
  51748. if (this.front)
  51749. this.front.clipTo(bsp);
  51750. if (this.back)
  51751. this.back.clipTo(bsp);
  51752. };
  51753. // Return a list of all polygons in this BSP tree.
  51754. Node.prototype.allPolygons = function () {
  51755. var polygons = this.polygons.slice();
  51756. if (this.front)
  51757. polygons = polygons.concat(this.front.allPolygons());
  51758. if (this.back)
  51759. polygons = polygons.concat(this.back.allPolygons());
  51760. return polygons;
  51761. };
  51762. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  51763. // new polygons are filtered down to the bottom of the tree and become new
  51764. // nodes there. Each set of polygons is partitioned using the first polygon
  51765. // (no heuristic is used to pick a good split).
  51766. Node.prototype.build = function (polygons) {
  51767. if (!polygons.length)
  51768. return;
  51769. if (!this.plane)
  51770. this.plane = polygons[0].plane.clone();
  51771. var front = [], back = [];
  51772. for (var i = 0; i < polygons.length; i++) {
  51773. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  51774. }
  51775. if (front.length) {
  51776. if (!this.front)
  51777. this.front = new Node();
  51778. this.front.build(front);
  51779. }
  51780. if (back.length) {
  51781. if (!this.back)
  51782. this.back = new Node();
  51783. this.back.build(back);
  51784. }
  51785. };
  51786. return Node;
  51787. }());
  51788. var CSG = (function () {
  51789. function CSG() {
  51790. this.polygons = new Array();
  51791. }
  51792. // Convert BABYLON.Mesh to BABYLON.CSG
  51793. CSG.FromMesh = function (mesh) {
  51794. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  51795. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  51796. if (mesh instanceof BABYLON.Mesh) {
  51797. mesh.computeWorldMatrix(true);
  51798. matrix = mesh.getWorldMatrix();
  51799. meshPosition = mesh.position.clone();
  51800. meshRotation = mesh.rotation.clone();
  51801. if (mesh.rotationQuaternion) {
  51802. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  51803. }
  51804. meshScaling = mesh.scaling.clone();
  51805. }
  51806. else {
  51807. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  51808. }
  51809. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  51810. var subMeshes = mesh.subMeshes;
  51811. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  51812. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  51813. vertices = [];
  51814. for (var j = 0; j < 3; j++) {
  51815. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  51816. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  51817. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  51818. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  51819. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  51820. vertex = new Vertex(position, normal, uv);
  51821. vertices.push(vertex);
  51822. }
  51823. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  51824. // To handle the case of degenerated triangle
  51825. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  51826. if (polygon.plane)
  51827. polygons.push(polygon);
  51828. }
  51829. }
  51830. var csg = CSG.FromPolygons(polygons);
  51831. csg.matrix = matrix;
  51832. csg.position = meshPosition;
  51833. csg.rotation = meshRotation;
  51834. csg.scaling = meshScaling;
  51835. csg.rotationQuaternion = meshRotationQuaternion;
  51836. currentCSGMeshId++;
  51837. return csg;
  51838. };
  51839. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  51840. CSG.FromPolygons = function (polygons) {
  51841. var csg = new CSG();
  51842. csg.polygons = polygons;
  51843. return csg;
  51844. };
  51845. CSG.prototype.clone = function () {
  51846. var csg = new CSG();
  51847. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  51848. csg.copyTransformAttributes(this);
  51849. return csg;
  51850. };
  51851. CSG.prototype.toPolygons = function () {
  51852. return this.polygons;
  51853. };
  51854. CSG.prototype.union = function (csg) {
  51855. var a = new Node(this.clone().polygons);
  51856. var b = new Node(csg.clone().polygons);
  51857. a.clipTo(b);
  51858. b.clipTo(a);
  51859. b.invert();
  51860. b.clipTo(a);
  51861. b.invert();
  51862. a.build(b.allPolygons());
  51863. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51864. };
  51865. CSG.prototype.unionInPlace = function (csg) {
  51866. var a = new Node(this.polygons);
  51867. var b = new Node(csg.polygons);
  51868. a.clipTo(b);
  51869. b.clipTo(a);
  51870. b.invert();
  51871. b.clipTo(a);
  51872. b.invert();
  51873. a.build(b.allPolygons());
  51874. this.polygons = a.allPolygons();
  51875. };
  51876. CSG.prototype.subtract = function (csg) {
  51877. var a = new Node(this.clone().polygons);
  51878. var b = new Node(csg.clone().polygons);
  51879. a.invert();
  51880. a.clipTo(b);
  51881. b.clipTo(a);
  51882. b.invert();
  51883. b.clipTo(a);
  51884. b.invert();
  51885. a.build(b.allPolygons());
  51886. a.invert();
  51887. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51888. };
  51889. CSG.prototype.subtractInPlace = function (csg) {
  51890. var a = new Node(this.polygons);
  51891. var b = new Node(csg.polygons);
  51892. a.invert();
  51893. a.clipTo(b);
  51894. b.clipTo(a);
  51895. b.invert();
  51896. b.clipTo(a);
  51897. b.invert();
  51898. a.build(b.allPolygons());
  51899. a.invert();
  51900. this.polygons = a.allPolygons();
  51901. };
  51902. CSG.prototype.intersect = function (csg) {
  51903. var a = new Node(this.clone().polygons);
  51904. var b = new Node(csg.clone().polygons);
  51905. a.invert();
  51906. b.clipTo(a);
  51907. b.invert();
  51908. a.clipTo(b);
  51909. b.clipTo(a);
  51910. a.build(b.allPolygons());
  51911. a.invert();
  51912. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  51913. };
  51914. CSG.prototype.intersectInPlace = function (csg) {
  51915. var a = new Node(this.polygons);
  51916. var b = new Node(csg.polygons);
  51917. a.invert();
  51918. b.clipTo(a);
  51919. b.invert();
  51920. a.clipTo(b);
  51921. b.clipTo(a);
  51922. a.build(b.allPolygons());
  51923. a.invert();
  51924. this.polygons = a.allPolygons();
  51925. };
  51926. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  51927. // not modified.
  51928. CSG.prototype.inverse = function () {
  51929. var csg = this.clone();
  51930. csg.inverseInPlace();
  51931. return csg;
  51932. };
  51933. CSG.prototype.inverseInPlace = function () {
  51934. this.polygons.map(function (p) { p.flip(); });
  51935. };
  51936. // This is used to keep meshes transformations so they can be restored
  51937. // when we build back a Babylon Mesh
  51938. // NB : All CSG operations are performed in world coordinates
  51939. CSG.prototype.copyTransformAttributes = function (csg) {
  51940. this.matrix = csg.matrix;
  51941. this.position = csg.position;
  51942. this.rotation = csg.rotation;
  51943. this.scaling = csg.scaling;
  51944. this.rotationQuaternion = csg.rotationQuaternion;
  51945. return this;
  51946. };
  51947. // Build Raw mesh from CSG
  51948. // Coordinates here are in world space
  51949. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  51950. var matrix = this.matrix.clone();
  51951. matrix.invert();
  51952. 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;
  51953. if (keepSubMeshes) {
  51954. // Sort Polygons, since subMeshes are indices range
  51955. polygons.sort(function (a, b) {
  51956. if (a.shared.meshId === b.shared.meshId) {
  51957. return a.shared.subMeshId - b.shared.subMeshId;
  51958. }
  51959. else {
  51960. return a.shared.meshId - b.shared.meshId;
  51961. }
  51962. });
  51963. }
  51964. for (var i = 0, il = polygons.length; i < il; i++) {
  51965. polygon = polygons[i];
  51966. // Building SubMeshes
  51967. if (!subMesh_dict[polygon.shared.meshId]) {
  51968. subMesh_dict[polygon.shared.meshId] = {};
  51969. }
  51970. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  51971. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  51972. indexStart: +Infinity,
  51973. indexEnd: -Infinity,
  51974. materialIndex: polygon.shared.materialIndex
  51975. };
  51976. }
  51977. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  51978. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  51979. polygonIndices[0] = 0;
  51980. polygonIndices[1] = j - 1;
  51981. polygonIndices[2] = j;
  51982. for (var k = 0; k < 3; k++) {
  51983. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  51984. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  51985. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  51986. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  51987. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  51988. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  51989. // Check if 2 points can be merged
  51990. if (!(typeof vertex_idx !== 'undefined' &&
  51991. normals[vertex_idx * 3] === localNormal.x &&
  51992. normals[vertex_idx * 3 + 1] === localNormal.y &&
  51993. normals[vertex_idx * 3 + 2] === localNormal.z &&
  51994. uvs[vertex_idx * 2] === uv.x &&
  51995. uvs[vertex_idx * 2 + 1] === uv.y)) {
  51996. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  51997. uvs.push(uv.x, uv.y);
  51998. normals.push(normal.x, normal.y, normal.z);
  51999. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  52000. }
  52001. indices.push(vertex_idx);
  52002. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  52003. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  52004. currentIndex++;
  52005. }
  52006. }
  52007. }
  52008. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  52009. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  52010. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  52011. mesh.setIndices(indices);
  52012. if (keepSubMeshes) {
  52013. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  52014. var materialIndexOffset = 0, materialMaxIndex;
  52015. mesh.subMeshes = new Array();
  52016. for (var m in subMesh_dict) {
  52017. materialMaxIndex = -1;
  52018. for (var sm in subMesh_dict[m]) {
  52019. subMesh_obj = subMesh_dict[m][sm];
  52020. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  52021. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  52022. }
  52023. materialIndexOffset += ++materialMaxIndex;
  52024. }
  52025. }
  52026. return mesh;
  52027. };
  52028. // Build Mesh from CSG taking material and transforms into account
  52029. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  52030. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  52031. mesh.material = material;
  52032. mesh.position.copyFrom(this.position);
  52033. mesh.rotation.copyFrom(this.rotation);
  52034. if (this.rotationQuaternion) {
  52035. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  52036. }
  52037. mesh.scaling.copyFrom(this.scaling);
  52038. mesh.computeWorldMatrix(true);
  52039. return mesh;
  52040. };
  52041. return CSG;
  52042. }());
  52043. BABYLON.CSG = CSG;
  52044. })(BABYLON || (BABYLON = {}));
  52045. var BABYLON;
  52046. (function (BABYLON) {
  52047. var VRDistortionCorrectionPostProcess = (function (_super) {
  52048. __extends(VRDistortionCorrectionPostProcess, _super);
  52049. //ANY
  52050. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  52051. var _this = this;
  52052. _super.call(this, name, "vrDistortionCorrection", [
  52053. 'LensCenter',
  52054. 'Scale',
  52055. 'ScaleIn',
  52056. 'HmdWarpParam'
  52057. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  52058. this._isRightEye = isRightEye;
  52059. this._distortionFactors = vrMetrics.distortionK;
  52060. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  52061. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  52062. this.onSizeChangedObservable.add(function () {
  52063. _this.aspectRatio = _this.width * .5 / _this.height;
  52064. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  52065. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  52066. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  52067. });
  52068. this.onApplyObservable.add(function (effect) {
  52069. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  52070. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  52071. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  52072. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  52073. });
  52074. }
  52075. return VRDistortionCorrectionPostProcess;
  52076. }(BABYLON.PostProcess));
  52077. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  52078. })(BABYLON || (BABYLON = {}));
  52079. // Mainly based on these 2 articles :
  52080. // 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
  52081. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  52082. var BABYLON;
  52083. (function (BABYLON) {
  52084. (function (JoystickAxis) {
  52085. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  52086. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  52087. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  52088. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  52089. var JoystickAxis = BABYLON.JoystickAxis;
  52090. var VirtualJoystick = (function () {
  52091. function VirtualJoystick(leftJoystick) {
  52092. var _this = this;
  52093. if (leftJoystick) {
  52094. this._leftJoystick = true;
  52095. }
  52096. else {
  52097. this._leftJoystick = false;
  52098. }
  52099. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  52100. VirtualJoystick._globalJoystickIndex++;
  52101. // By default left & right arrow keys are moving the X
  52102. // and up & down keys are moving the Y
  52103. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  52104. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  52105. this.reverseLeftRight = false;
  52106. this.reverseUpDown = false;
  52107. // collections of pointers
  52108. this._touches = new BABYLON.StringDictionary();
  52109. this.deltaPosition = BABYLON.Vector3.Zero();
  52110. this._joystickSensibility = 25;
  52111. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  52112. this._rotationSpeed = 25;
  52113. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  52114. this._rotateOnAxisRelativeToMesh = false;
  52115. this._onResize = function (evt) {
  52116. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  52117. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  52118. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  52119. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  52120. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  52121. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  52122. };
  52123. // injecting a canvas element on top of the canvas 3D game
  52124. if (!VirtualJoystick.vjCanvas) {
  52125. window.addEventListener("resize", this._onResize, false);
  52126. VirtualJoystick.vjCanvas = document.createElement("canvas");
  52127. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  52128. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  52129. VirtualJoystick.vjCanvas.width = window.innerWidth;
  52130. VirtualJoystick.vjCanvas.height = window.innerHeight;
  52131. VirtualJoystick.vjCanvas.style.width = "100%";
  52132. VirtualJoystick.vjCanvas.style.height = "100%";
  52133. VirtualJoystick.vjCanvas.style.position = "absolute";
  52134. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  52135. VirtualJoystick.vjCanvas.style.top = "0px";
  52136. VirtualJoystick.vjCanvas.style.left = "0px";
  52137. VirtualJoystick.vjCanvas.style.zIndex = "5";
  52138. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  52139. // Support for jQuery PEP polyfill
  52140. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  52141. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  52142. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  52143. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  52144. document.body.appendChild(VirtualJoystick.vjCanvas);
  52145. }
  52146. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  52147. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  52148. this.pressed = false;
  52149. // default joystick color
  52150. this._joystickColor = "cyan";
  52151. this._joystickPointerID = -1;
  52152. // current joystick position
  52153. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  52154. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  52155. // origin joystick position
  52156. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  52157. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  52158. this._onPointerDownHandlerRef = function (evt) {
  52159. _this._onPointerDown(evt);
  52160. };
  52161. this._onPointerMoveHandlerRef = function (evt) {
  52162. _this._onPointerMove(evt);
  52163. };
  52164. this._onPointerOutHandlerRef = function (evt) {
  52165. _this._onPointerUp(evt);
  52166. };
  52167. this._onPointerUpHandlerRef = function (evt) {
  52168. _this._onPointerUp(evt);
  52169. };
  52170. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  52171. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  52172. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  52173. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  52174. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  52175. evt.preventDefault(); // Disables system menu
  52176. }, false);
  52177. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  52178. }
  52179. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  52180. this._joystickSensibility = newJoystickSensibility;
  52181. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  52182. };
  52183. VirtualJoystick.prototype._onPointerDown = function (e) {
  52184. var positionOnScreenCondition;
  52185. e.preventDefault();
  52186. if (this._leftJoystick === true) {
  52187. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  52188. }
  52189. else {
  52190. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  52191. }
  52192. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  52193. // First contact will be dedicated to the virtual joystick
  52194. this._joystickPointerID = e.pointerId;
  52195. this._joystickPointerStartPos.x = e.clientX;
  52196. this._joystickPointerStartPos.y = e.clientY;
  52197. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  52198. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  52199. this._deltaJoystickVector.x = 0;
  52200. this._deltaJoystickVector.y = 0;
  52201. this.pressed = true;
  52202. this._touches.add(e.pointerId.toString(), e);
  52203. }
  52204. else {
  52205. // You can only trigger the action buttons with a joystick declared
  52206. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  52207. this._action();
  52208. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  52209. }
  52210. }
  52211. };
  52212. VirtualJoystick.prototype._onPointerMove = function (e) {
  52213. // If the current pointer is the one associated to the joystick (first touch contact)
  52214. if (this._joystickPointerID == e.pointerId) {
  52215. this._joystickPointerPos.x = e.clientX;
  52216. this._joystickPointerPos.y = e.clientY;
  52217. this._deltaJoystickVector = this._joystickPointerPos.clone();
  52218. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  52219. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  52220. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  52221. switch (this._axisTargetedByLeftAndRight) {
  52222. case JoystickAxis.X:
  52223. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  52224. break;
  52225. case JoystickAxis.Y:
  52226. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  52227. break;
  52228. case JoystickAxis.Z:
  52229. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  52230. break;
  52231. }
  52232. var directionUpDown = this.reverseUpDown ? 1 : -1;
  52233. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  52234. switch (this._axisTargetedByUpAndDown) {
  52235. case JoystickAxis.X:
  52236. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  52237. break;
  52238. case JoystickAxis.Y:
  52239. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  52240. break;
  52241. case JoystickAxis.Z:
  52242. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  52243. break;
  52244. }
  52245. }
  52246. else {
  52247. var data = this._touches.get(e.pointerId.toString());
  52248. if (data) {
  52249. data.x = e.clientX;
  52250. data.y = e.clientY;
  52251. }
  52252. }
  52253. };
  52254. VirtualJoystick.prototype._onPointerUp = function (e) {
  52255. if (this._joystickPointerID == e.pointerId) {
  52256. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  52257. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  52258. this._joystickPointerID = -1;
  52259. this.pressed = false;
  52260. }
  52261. else {
  52262. var touch = this._touches.get(e.pointerId.toString());
  52263. if (touch) {
  52264. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  52265. }
  52266. }
  52267. this._deltaJoystickVector.x = 0;
  52268. this._deltaJoystickVector.y = 0;
  52269. this._touches.remove(e.pointerId.toString());
  52270. };
  52271. /**
  52272. * Change the color of the virtual joystick
  52273. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  52274. */
  52275. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  52276. this._joystickColor = newColor;
  52277. };
  52278. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  52279. this._action = action;
  52280. };
  52281. // Define which axis you'd like to control for left & right
  52282. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  52283. switch (axis) {
  52284. case JoystickAxis.X:
  52285. case JoystickAxis.Y:
  52286. case JoystickAxis.Z:
  52287. this._axisTargetedByLeftAndRight = axis;
  52288. break;
  52289. default:
  52290. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  52291. break;
  52292. }
  52293. };
  52294. // Define which axis you'd like to control for up & down
  52295. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  52296. switch (axis) {
  52297. case JoystickAxis.X:
  52298. case JoystickAxis.Y:
  52299. case JoystickAxis.Z:
  52300. this._axisTargetedByUpAndDown = axis;
  52301. break;
  52302. default:
  52303. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  52304. break;
  52305. }
  52306. };
  52307. VirtualJoystick.prototype._clearCanvas = function () {
  52308. if (this._leftJoystick) {
  52309. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  52310. }
  52311. else {
  52312. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  52313. }
  52314. };
  52315. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  52316. var _this = this;
  52317. if (this.pressed) {
  52318. this._touches.forEach(function (touch) {
  52319. if (touch.pointerId === _this._joystickPointerID) {
  52320. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  52321. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  52322. VirtualJoystick.vjCanvasContext.beginPath();
  52323. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  52324. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52325. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  52326. VirtualJoystick.vjCanvasContext.stroke();
  52327. VirtualJoystick.vjCanvasContext.closePath();
  52328. VirtualJoystick.vjCanvasContext.beginPath();
  52329. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52330. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  52331. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  52332. VirtualJoystick.vjCanvasContext.stroke();
  52333. VirtualJoystick.vjCanvasContext.closePath();
  52334. VirtualJoystick.vjCanvasContext.beginPath();
  52335. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  52336. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  52337. VirtualJoystick.vjCanvasContext.stroke();
  52338. VirtualJoystick.vjCanvasContext.closePath();
  52339. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  52340. }
  52341. else {
  52342. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  52343. VirtualJoystick.vjCanvasContext.beginPath();
  52344. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  52345. VirtualJoystick.vjCanvasContext.beginPath();
  52346. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  52347. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  52348. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  52349. VirtualJoystick.vjCanvasContext.stroke();
  52350. VirtualJoystick.vjCanvasContext.closePath();
  52351. touch.prevX = touch.x;
  52352. touch.prevY = touch.y;
  52353. }
  52354. ;
  52355. });
  52356. }
  52357. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  52358. };
  52359. VirtualJoystick.prototype.releaseCanvas = function () {
  52360. if (VirtualJoystick.vjCanvas) {
  52361. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  52362. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  52363. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  52364. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  52365. window.removeEventListener("resize", this._onResize);
  52366. document.body.removeChild(VirtualJoystick.vjCanvas);
  52367. VirtualJoystick.vjCanvas = null;
  52368. }
  52369. };
  52370. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  52371. VirtualJoystick._globalJoystickIndex = 0;
  52372. return VirtualJoystick;
  52373. }());
  52374. BABYLON.VirtualJoystick = VirtualJoystick;
  52375. })(BABYLON || (BABYLON = {}));
  52376. var BABYLON;
  52377. (function (BABYLON) {
  52378. // We're mainly based on the logic defined into the FreeCamera code
  52379. var VirtualJoysticksCamera = (function (_super) {
  52380. __extends(VirtualJoysticksCamera, _super);
  52381. function VirtualJoysticksCamera(name, position, scene) {
  52382. _super.call(this, name, position, scene);
  52383. this.inputs.addVirtualJoystick();
  52384. }
  52385. return VirtualJoysticksCamera;
  52386. }(BABYLON.FreeCamera));
  52387. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  52388. })(BABYLON || (BABYLON = {}));
  52389. var BABYLON;
  52390. (function (BABYLON) {
  52391. var FreeCameraVirtualJoystickInput = (function () {
  52392. function FreeCameraVirtualJoystickInput() {
  52393. }
  52394. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  52395. return this._leftjoystick;
  52396. };
  52397. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  52398. return this._rightjoystick;
  52399. };
  52400. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  52401. if (this._leftjoystick) {
  52402. var camera = this.camera;
  52403. var speed = camera._computeLocalCameraSpeed() * 50;
  52404. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  52405. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  52406. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  52407. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  52408. if (!this._leftjoystick.pressed) {
  52409. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  52410. }
  52411. if (!this._rightjoystick.pressed) {
  52412. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  52413. }
  52414. }
  52415. };
  52416. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  52417. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  52418. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  52419. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  52420. this._leftjoystick.setJoystickSensibility(0.15);
  52421. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  52422. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  52423. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  52424. this._rightjoystick.reverseUpDown = true;
  52425. this._rightjoystick.setJoystickSensibility(0.05);
  52426. this._rightjoystick.setJoystickColor("yellow");
  52427. };
  52428. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  52429. this._leftjoystick.releaseCanvas();
  52430. this._rightjoystick.releaseCanvas();
  52431. };
  52432. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  52433. return "FreeCameraVirtualJoystickInput";
  52434. };
  52435. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  52436. return "virtualJoystick";
  52437. };
  52438. return FreeCameraVirtualJoystickInput;
  52439. }());
  52440. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  52441. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  52442. })(BABYLON || (BABYLON = {}));
  52443. var BABYLON;
  52444. (function (BABYLON) {
  52445. var AnaglyphPostProcess = (function (_super) {
  52446. __extends(AnaglyphPostProcess, _super);
  52447. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  52448. var _this = this;
  52449. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  52450. this._passedProcess = rigCameras[0]._rigPostProcess;
  52451. this.onApplyObservable.add(function (effect) {
  52452. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  52453. });
  52454. }
  52455. return AnaglyphPostProcess;
  52456. }(BABYLON.PostProcess));
  52457. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  52458. })(BABYLON || (BABYLON = {}));
  52459. var BABYLON;
  52460. (function (BABYLON) {
  52461. var OutlineRenderer = (function () {
  52462. function OutlineRenderer(scene) {
  52463. this._scene = scene;
  52464. }
  52465. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  52466. var _this = this;
  52467. if (useOverlay === void 0) { useOverlay = false; }
  52468. var scene = this._scene;
  52469. var engine = this._scene.getEngine();
  52470. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  52471. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  52472. return;
  52473. }
  52474. var mesh = subMesh.getRenderingMesh();
  52475. var material = subMesh.getMaterial();
  52476. engine.enableEffect(this._effect);
  52477. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  52478. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  52479. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52480. // Bones
  52481. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52482. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52483. }
  52484. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  52485. // Alpha test
  52486. if (material && material.needAlphaTesting()) {
  52487. var alphaTexture = material.getAlphaTestTexture();
  52488. this._effect.setTexture("diffuseSampler", alphaTexture);
  52489. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52490. }
  52491. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  52492. };
  52493. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  52494. var defines = [];
  52495. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  52496. var mesh = subMesh.getMesh();
  52497. var material = subMesh.getMaterial();
  52498. // Alpha test
  52499. if (material && material.needAlphaTesting()) {
  52500. defines.push("#define ALPHATEST");
  52501. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52502. attribs.push(BABYLON.VertexBuffer.UVKind);
  52503. defines.push("#define UV1");
  52504. }
  52505. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52506. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52507. defines.push("#define UV2");
  52508. }
  52509. }
  52510. // Bones
  52511. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52512. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52513. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52514. if (mesh.numBoneInfluencers > 4) {
  52515. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52516. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52517. }
  52518. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52519. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52520. }
  52521. else {
  52522. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52523. }
  52524. // Instances
  52525. if (useInstances) {
  52526. defines.push("#define INSTANCES");
  52527. attribs.push("world0");
  52528. attribs.push("world1");
  52529. attribs.push("world2");
  52530. attribs.push("world3");
  52531. }
  52532. // Get correct effect
  52533. var join = defines.join("\n");
  52534. if (this._cachedDefines !== join) {
  52535. this._cachedDefines = join;
  52536. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  52537. }
  52538. return this._effect.isReady();
  52539. };
  52540. return OutlineRenderer;
  52541. }());
  52542. BABYLON.OutlineRenderer = OutlineRenderer;
  52543. })(BABYLON || (BABYLON = {}));
  52544. var BABYLON;
  52545. (function (BABYLON) {
  52546. var MeshAssetTask = (function () {
  52547. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  52548. this.name = name;
  52549. this.meshesNames = meshesNames;
  52550. this.rootUrl = rootUrl;
  52551. this.sceneFilename = sceneFilename;
  52552. this.isCompleted = false;
  52553. }
  52554. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52555. var _this = this;
  52556. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  52557. _this.loadedMeshes = meshes;
  52558. _this.loadedParticleSystems = particleSystems;
  52559. _this.loadedSkeletons = skeletons;
  52560. _this.isCompleted = true;
  52561. if (_this.onSuccess) {
  52562. _this.onSuccess(_this);
  52563. }
  52564. onSuccess();
  52565. }, null, function () {
  52566. if (_this.onError) {
  52567. _this.onError(_this);
  52568. }
  52569. onError();
  52570. });
  52571. };
  52572. return MeshAssetTask;
  52573. }());
  52574. BABYLON.MeshAssetTask = MeshAssetTask;
  52575. var TextFileAssetTask = (function () {
  52576. function TextFileAssetTask(name, url) {
  52577. this.name = name;
  52578. this.url = url;
  52579. this.isCompleted = false;
  52580. }
  52581. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52582. var _this = this;
  52583. BABYLON.Tools.LoadFile(this.url, function (data) {
  52584. _this.text = data;
  52585. _this.isCompleted = true;
  52586. if (_this.onSuccess) {
  52587. _this.onSuccess(_this);
  52588. }
  52589. onSuccess();
  52590. }, null, scene.database, false, function () {
  52591. if (_this.onError) {
  52592. _this.onError(_this);
  52593. }
  52594. onError();
  52595. });
  52596. };
  52597. return TextFileAssetTask;
  52598. }());
  52599. BABYLON.TextFileAssetTask = TextFileAssetTask;
  52600. var BinaryFileAssetTask = (function () {
  52601. function BinaryFileAssetTask(name, url) {
  52602. this.name = name;
  52603. this.url = url;
  52604. this.isCompleted = false;
  52605. }
  52606. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52607. var _this = this;
  52608. BABYLON.Tools.LoadFile(this.url, function (data) {
  52609. _this.data = data;
  52610. _this.isCompleted = true;
  52611. if (_this.onSuccess) {
  52612. _this.onSuccess(_this);
  52613. }
  52614. onSuccess();
  52615. }, null, scene.database, true, function () {
  52616. if (_this.onError) {
  52617. _this.onError(_this);
  52618. }
  52619. onError();
  52620. });
  52621. };
  52622. return BinaryFileAssetTask;
  52623. }());
  52624. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  52625. var ImageAssetTask = (function () {
  52626. function ImageAssetTask(name, url) {
  52627. this.name = name;
  52628. this.url = url;
  52629. this.isCompleted = false;
  52630. }
  52631. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52632. var _this = this;
  52633. var img = new Image();
  52634. BABYLON.Tools.SetCorsBehavior(this.url, img);
  52635. img.onload = function () {
  52636. _this.image = img;
  52637. _this.isCompleted = true;
  52638. if (_this.onSuccess) {
  52639. _this.onSuccess(_this);
  52640. }
  52641. onSuccess();
  52642. };
  52643. img.onerror = function () {
  52644. if (_this.onError) {
  52645. _this.onError(_this);
  52646. }
  52647. onError();
  52648. };
  52649. img.src = this.url;
  52650. };
  52651. return ImageAssetTask;
  52652. }());
  52653. BABYLON.ImageAssetTask = ImageAssetTask;
  52654. var TextureAssetTask = (function () {
  52655. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  52656. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52657. this.name = name;
  52658. this.url = url;
  52659. this.noMipmap = noMipmap;
  52660. this.invertY = invertY;
  52661. this.samplingMode = samplingMode;
  52662. this.isCompleted = false;
  52663. }
  52664. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  52665. var _this = this;
  52666. var onload = function () {
  52667. _this.isCompleted = true;
  52668. if (_this.onSuccess) {
  52669. _this.onSuccess(_this);
  52670. }
  52671. onSuccess();
  52672. };
  52673. var onerror = function () {
  52674. if (_this.onError) {
  52675. _this.onError(_this);
  52676. }
  52677. onError();
  52678. };
  52679. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  52680. };
  52681. return TextureAssetTask;
  52682. }());
  52683. BABYLON.TextureAssetTask = TextureAssetTask;
  52684. var AssetsManager = (function () {
  52685. function AssetsManager(scene) {
  52686. this._tasks = new Array();
  52687. this._waitingTasksCount = 0;
  52688. this.useDefaultLoadingScreen = true;
  52689. this._scene = scene;
  52690. }
  52691. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  52692. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  52693. this._tasks.push(task);
  52694. return task;
  52695. };
  52696. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  52697. var task = new TextFileAssetTask(taskName, url);
  52698. this._tasks.push(task);
  52699. return task;
  52700. };
  52701. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  52702. var task = new BinaryFileAssetTask(taskName, url);
  52703. this._tasks.push(task);
  52704. return task;
  52705. };
  52706. AssetsManager.prototype.addImageTask = function (taskName, url) {
  52707. var task = new ImageAssetTask(taskName, url);
  52708. this._tasks.push(task);
  52709. return task;
  52710. };
  52711. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  52712. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  52713. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  52714. this._tasks.push(task);
  52715. return task;
  52716. };
  52717. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  52718. this._waitingTasksCount--;
  52719. if (this._waitingTasksCount === 0) {
  52720. if (this.onFinish) {
  52721. this.onFinish(this._tasks);
  52722. }
  52723. this._scene.getEngine().hideLoadingUI();
  52724. }
  52725. };
  52726. AssetsManager.prototype._runTask = function (task) {
  52727. var _this = this;
  52728. task.run(this._scene, function () {
  52729. if (_this.onTaskSuccess) {
  52730. _this.onTaskSuccess(task);
  52731. }
  52732. _this._decreaseWaitingTasksCount();
  52733. }, function () {
  52734. if (_this.onTaskError) {
  52735. _this.onTaskError(task);
  52736. }
  52737. _this._decreaseWaitingTasksCount();
  52738. });
  52739. };
  52740. AssetsManager.prototype.reset = function () {
  52741. this._tasks = new Array();
  52742. return this;
  52743. };
  52744. AssetsManager.prototype.load = function () {
  52745. this._waitingTasksCount = this._tasks.length;
  52746. if (this._waitingTasksCount === 0) {
  52747. if (this.onFinish) {
  52748. this.onFinish(this._tasks);
  52749. }
  52750. return this;
  52751. }
  52752. if (this.useDefaultLoadingScreen) {
  52753. this._scene.getEngine().displayLoadingUI();
  52754. }
  52755. for (var index = 0; index < this._tasks.length; index++) {
  52756. var task = this._tasks[index];
  52757. this._runTask(task);
  52758. }
  52759. return this;
  52760. };
  52761. return AssetsManager;
  52762. }());
  52763. BABYLON.AssetsManager = AssetsManager;
  52764. })(BABYLON || (BABYLON = {}));
  52765. var BABYLON;
  52766. (function (BABYLON) {
  52767. var VRCameraMetrics = (function () {
  52768. function VRCameraMetrics() {
  52769. this.compensateDistortion = true;
  52770. }
  52771. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  52772. get: function () {
  52773. return this.hResolution / (2 * this.vResolution);
  52774. },
  52775. enumerable: true,
  52776. configurable: true
  52777. });
  52778. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  52779. get: function () {
  52780. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  52781. },
  52782. enumerable: true,
  52783. configurable: true
  52784. });
  52785. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  52786. get: function () {
  52787. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  52788. var h = (4 * meters) / this.hScreenSize;
  52789. return BABYLON.Matrix.Translation(h, 0, 0);
  52790. },
  52791. enumerable: true,
  52792. configurable: true
  52793. });
  52794. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  52795. get: function () {
  52796. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  52797. var h = (4 * meters) / this.hScreenSize;
  52798. return BABYLON.Matrix.Translation(-h, 0, 0);
  52799. },
  52800. enumerable: true,
  52801. configurable: true
  52802. });
  52803. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  52804. get: function () {
  52805. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  52806. },
  52807. enumerable: true,
  52808. configurable: true
  52809. });
  52810. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  52811. get: function () {
  52812. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  52813. },
  52814. enumerable: true,
  52815. configurable: true
  52816. });
  52817. VRCameraMetrics.GetDefault = function () {
  52818. var result = new VRCameraMetrics();
  52819. result.hResolution = 1280;
  52820. result.vResolution = 800;
  52821. result.hScreenSize = 0.149759993;
  52822. result.vScreenSize = 0.0935999975;
  52823. result.vScreenCenter = 0.0467999987,
  52824. result.eyeToScreenDistance = 0.0410000011;
  52825. result.lensSeparationDistance = 0.0635000020;
  52826. result.interpupillaryDistance = 0.0640000030;
  52827. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  52828. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  52829. result.postProcessScaleFactor = 1.714605507808412;
  52830. result.lensCenterOffset = 0.151976421;
  52831. return result;
  52832. };
  52833. return VRCameraMetrics;
  52834. }());
  52835. BABYLON.VRCameraMetrics = VRCameraMetrics;
  52836. })(BABYLON || (BABYLON = {}));
  52837. var BABYLON;
  52838. (function (BABYLON) {
  52839. var WebVRFreeCamera = (function (_super) {
  52840. __extends(WebVRFreeCamera, _super);
  52841. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  52842. var _this = this;
  52843. if (compensateDistortion === void 0) { compensateDistortion = false; }
  52844. if (webVROptions === void 0) { webVROptions = {}; }
  52845. _super.call(this, name, position, scene);
  52846. this.webVROptions = webVROptions;
  52847. this._vrDevice = null;
  52848. this._cacheState = null;
  52849. this._vrEnabled = false;
  52850. //enable VR
  52851. this.getEngine().initWebVR();
  52852. if (!this.getEngine().vrDisplaysPromise) {
  52853. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  52854. }
  52855. else {
  52856. //TODO get the metrics updated using the device's eye parameters!
  52857. //TODO also check that the device has the right capabilities!
  52858. this.getEngine().vrDisplaysPromise.then(function (devices) {
  52859. if (devices.length > 0) {
  52860. _this._vrEnabled = true;
  52861. if (_this.webVROptions.displayName) {
  52862. var found = devices.some(function (device) {
  52863. if (device.displayName === _this.webVROptions.displayName) {
  52864. _this._vrDevice = device;
  52865. return true;
  52866. }
  52867. else {
  52868. return false;
  52869. }
  52870. });
  52871. if (!found) {
  52872. _this._vrDevice = devices[0];
  52873. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  52874. }
  52875. }
  52876. else {
  52877. //choose the first one
  52878. _this._vrDevice = devices[0];
  52879. }
  52880. //reset the rig parameters.
  52881. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice });
  52882. }
  52883. else {
  52884. BABYLON.Tools.Error("No WebVR devices found!");
  52885. }
  52886. });
  52887. }
  52888. this.rotationQuaternion = new BABYLON.Quaternion();
  52889. this._quaternionCache = new BABYLON.Quaternion();
  52890. }
  52891. WebVRFreeCamera.prototype._checkInputs = function () {
  52892. if (this._vrEnabled) {
  52893. var currentPost = this._vrDevice.getPose();
  52894. //make sure we have data
  52895. if (currentPost && currentPost.orientation) {
  52896. this._cacheState = currentPost;
  52897. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], this._cacheState.orientation[2], this._cacheState.orientation[3]);
  52898. if (this.webVROptions.trackPosition && this._cacheState.position) {
  52899. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  52900. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  52901. }
  52902. //Flip in XY plane
  52903. this.rotationQuaternion.z *= -1;
  52904. this.rotationQuaternion.w *= -1;
  52905. }
  52906. }
  52907. _super.prototype._checkInputs.call(this);
  52908. };
  52909. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  52910. _super.prototype.attachControl.call(this, element, noPreventDefault);
  52911. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  52912. if (this._vrEnabled) {
  52913. this.getEngine().enableVR(this._vrDevice);
  52914. }
  52915. };
  52916. WebVRFreeCamera.prototype.detachControl = function (element) {
  52917. _super.prototype.detachControl.call(this, element);
  52918. this._vrEnabled = false;
  52919. this.getEngine().disableVR();
  52920. };
  52921. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  52922. //Backwards comp.
  52923. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  52924. //this.getEngine().switchFullscreen(requestPointerlock);
  52925. };
  52926. WebVRFreeCamera.prototype.getTypeName = function () {
  52927. return "WebVRFreeCamera";
  52928. };
  52929. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  52930. //uses the vrDisplay's "resetPose()".
  52931. //pitch and roll won't be affected.
  52932. this._vrDevice.resetPose();
  52933. };
  52934. return WebVRFreeCamera;
  52935. }(BABYLON.FreeCamera));
  52936. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  52937. })(BABYLON || (BABYLON = {}));
  52938. var BABYLON;
  52939. (function (BABYLON) {
  52940. // Standard optimizations
  52941. var SceneOptimization = (function () {
  52942. function SceneOptimization(priority) {
  52943. if (priority === void 0) { priority = 0; }
  52944. this.priority = priority;
  52945. this.apply = function (scene) {
  52946. return true; // Return true if everything that can be done was applied
  52947. };
  52948. }
  52949. return SceneOptimization;
  52950. }());
  52951. BABYLON.SceneOptimization = SceneOptimization;
  52952. var TextureOptimization = (function (_super) {
  52953. __extends(TextureOptimization, _super);
  52954. function TextureOptimization(priority, maximumSize) {
  52955. var _this = this;
  52956. if (priority === void 0) { priority = 0; }
  52957. if (maximumSize === void 0) { maximumSize = 1024; }
  52958. _super.call(this, priority);
  52959. this.priority = priority;
  52960. this.maximumSize = maximumSize;
  52961. this.apply = function (scene) {
  52962. var allDone = true;
  52963. for (var index = 0; index < scene.textures.length; index++) {
  52964. var texture = scene.textures[index];
  52965. if (!texture.canRescale) {
  52966. continue;
  52967. }
  52968. var currentSize = texture.getSize();
  52969. var maxDimension = Math.max(currentSize.width, currentSize.height);
  52970. if (maxDimension > _this.maximumSize) {
  52971. texture.scale(0.5);
  52972. allDone = false;
  52973. }
  52974. }
  52975. return allDone;
  52976. };
  52977. }
  52978. return TextureOptimization;
  52979. }(SceneOptimization));
  52980. BABYLON.TextureOptimization = TextureOptimization;
  52981. var HardwareScalingOptimization = (function (_super) {
  52982. __extends(HardwareScalingOptimization, _super);
  52983. function HardwareScalingOptimization(priority, maximumScale) {
  52984. var _this = this;
  52985. if (priority === void 0) { priority = 0; }
  52986. if (maximumScale === void 0) { maximumScale = 2; }
  52987. _super.call(this, priority);
  52988. this.priority = priority;
  52989. this.maximumScale = maximumScale;
  52990. this._currentScale = 1;
  52991. this.apply = function (scene) {
  52992. _this._currentScale++;
  52993. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  52994. return _this._currentScale >= _this.maximumScale;
  52995. };
  52996. }
  52997. return HardwareScalingOptimization;
  52998. }(SceneOptimization));
  52999. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  53000. var ShadowsOptimization = (function (_super) {
  53001. __extends(ShadowsOptimization, _super);
  53002. function ShadowsOptimization() {
  53003. _super.apply(this, arguments);
  53004. this.apply = function (scene) {
  53005. scene.shadowsEnabled = false;
  53006. return true;
  53007. };
  53008. }
  53009. return ShadowsOptimization;
  53010. }(SceneOptimization));
  53011. BABYLON.ShadowsOptimization = ShadowsOptimization;
  53012. var PostProcessesOptimization = (function (_super) {
  53013. __extends(PostProcessesOptimization, _super);
  53014. function PostProcessesOptimization() {
  53015. _super.apply(this, arguments);
  53016. this.apply = function (scene) {
  53017. scene.postProcessesEnabled = false;
  53018. return true;
  53019. };
  53020. }
  53021. return PostProcessesOptimization;
  53022. }(SceneOptimization));
  53023. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  53024. var LensFlaresOptimization = (function (_super) {
  53025. __extends(LensFlaresOptimization, _super);
  53026. function LensFlaresOptimization() {
  53027. _super.apply(this, arguments);
  53028. this.apply = function (scene) {
  53029. scene.lensFlaresEnabled = false;
  53030. return true;
  53031. };
  53032. }
  53033. return LensFlaresOptimization;
  53034. }(SceneOptimization));
  53035. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  53036. var ParticlesOptimization = (function (_super) {
  53037. __extends(ParticlesOptimization, _super);
  53038. function ParticlesOptimization() {
  53039. _super.apply(this, arguments);
  53040. this.apply = function (scene) {
  53041. scene.particlesEnabled = false;
  53042. return true;
  53043. };
  53044. }
  53045. return ParticlesOptimization;
  53046. }(SceneOptimization));
  53047. BABYLON.ParticlesOptimization = ParticlesOptimization;
  53048. var RenderTargetsOptimization = (function (_super) {
  53049. __extends(RenderTargetsOptimization, _super);
  53050. function RenderTargetsOptimization() {
  53051. _super.apply(this, arguments);
  53052. this.apply = function (scene) {
  53053. scene.renderTargetsEnabled = false;
  53054. return true;
  53055. };
  53056. }
  53057. return RenderTargetsOptimization;
  53058. }(SceneOptimization));
  53059. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  53060. var MergeMeshesOptimization = (function (_super) {
  53061. __extends(MergeMeshesOptimization, _super);
  53062. function MergeMeshesOptimization() {
  53063. var _this = this;
  53064. _super.apply(this, arguments);
  53065. this._canBeMerged = function (abstractMesh) {
  53066. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  53067. return false;
  53068. }
  53069. var mesh = abstractMesh;
  53070. if (!mesh.isVisible || !mesh.isEnabled()) {
  53071. return false;
  53072. }
  53073. if (mesh.instances.length > 0) {
  53074. return false;
  53075. }
  53076. if (mesh.skeleton || mesh.hasLODLevels) {
  53077. return false;
  53078. }
  53079. if (mesh.parent) {
  53080. return false;
  53081. }
  53082. return true;
  53083. };
  53084. this.apply = function (scene, updateSelectionTree) {
  53085. var globalPool = scene.meshes.slice(0);
  53086. var globalLength = globalPool.length;
  53087. for (var index = 0; index < globalLength; index++) {
  53088. var currentPool = new Array();
  53089. var current = globalPool[index];
  53090. // Checks
  53091. if (!_this._canBeMerged(current)) {
  53092. continue;
  53093. }
  53094. currentPool.push(current);
  53095. // Find compatible meshes
  53096. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  53097. var otherMesh = globalPool[subIndex];
  53098. if (!_this._canBeMerged(otherMesh)) {
  53099. continue;
  53100. }
  53101. if (otherMesh.material !== current.material) {
  53102. continue;
  53103. }
  53104. if (otherMesh.checkCollisions !== current.checkCollisions) {
  53105. continue;
  53106. }
  53107. currentPool.push(otherMesh);
  53108. globalLength--;
  53109. globalPool.splice(subIndex, 1);
  53110. subIndex--;
  53111. }
  53112. if (currentPool.length < 2) {
  53113. continue;
  53114. }
  53115. // Merge meshes
  53116. BABYLON.Mesh.MergeMeshes(currentPool);
  53117. }
  53118. if (updateSelectionTree != undefined) {
  53119. if (updateSelectionTree) {
  53120. scene.createOrUpdateSelectionOctree();
  53121. }
  53122. }
  53123. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  53124. scene.createOrUpdateSelectionOctree();
  53125. }
  53126. return true;
  53127. };
  53128. }
  53129. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  53130. get: function () {
  53131. return MergeMeshesOptimization._UpdateSelectionTree;
  53132. },
  53133. set: function (value) {
  53134. MergeMeshesOptimization._UpdateSelectionTree = value;
  53135. },
  53136. enumerable: true,
  53137. configurable: true
  53138. });
  53139. MergeMeshesOptimization._UpdateSelectionTree = false;
  53140. return MergeMeshesOptimization;
  53141. }(SceneOptimization));
  53142. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  53143. // Options
  53144. var SceneOptimizerOptions = (function () {
  53145. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  53146. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  53147. if (trackerDuration === void 0) { trackerDuration = 2000; }
  53148. this.targetFrameRate = targetFrameRate;
  53149. this.trackerDuration = trackerDuration;
  53150. this.optimizations = new Array();
  53151. }
  53152. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  53153. var result = new SceneOptimizerOptions(targetFrameRate);
  53154. var priority = 0;
  53155. result.optimizations.push(new MergeMeshesOptimization(priority));
  53156. result.optimizations.push(new ShadowsOptimization(priority));
  53157. result.optimizations.push(new LensFlaresOptimization(priority));
  53158. // Next priority
  53159. priority++;
  53160. result.optimizations.push(new PostProcessesOptimization(priority));
  53161. result.optimizations.push(new ParticlesOptimization(priority));
  53162. // Next priority
  53163. priority++;
  53164. result.optimizations.push(new TextureOptimization(priority, 1024));
  53165. return result;
  53166. };
  53167. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  53168. var result = new SceneOptimizerOptions(targetFrameRate);
  53169. var priority = 0;
  53170. result.optimizations.push(new MergeMeshesOptimization(priority));
  53171. result.optimizations.push(new ShadowsOptimization(priority));
  53172. result.optimizations.push(new LensFlaresOptimization(priority));
  53173. // Next priority
  53174. priority++;
  53175. result.optimizations.push(new PostProcessesOptimization(priority));
  53176. result.optimizations.push(new ParticlesOptimization(priority));
  53177. // Next priority
  53178. priority++;
  53179. result.optimizations.push(new TextureOptimization(priority, 512));
  53180. // Next priority
  53181. priority++;
  53182. result.optimizations.push(new RenderTargetsOptimization(priority));
  53183. // Next priority
  53184. priority++;
  53185. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  53186. return result;
  53187. };
  53188. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  53189. var result = new SceneOptimizerOptions(targetFrameRate);
  53190. var priority = 0;
  53191. result.optimizations.push(new MergeMeshesOptimization(priority));
  53192. result.optimizations.push(new ShadowsOptimization(priority));
  53193. result.optimizations.push(new LensFlaresOptimization(priority));
  53194. // Next priority
  53195. priority++;
  53196. result.optimizations.push(new PostProcessesOptimization(priority));
  53197. result.optimizations.push(new ParticlesOptimization(priority));
  53198. // Next priority
  53199. priority++;
  53200. result.optimizations.push(new TextureOptimization(priority, 256));
  53201. // Next priority
  53202. priority++;
  53203. result.optimizations.push(new RenderTargetsOptimization(priority));
  53204. // Next priority
  53205. priority++;
  53206. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  53207. return result;
  53208. };
  53209. return SceneOptimizerOptions;
  53210. }());
  53211. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  53212. // Scene optimizer tool
  53213. var SceneOptimizer = (function () {
  53214. function SceneOptimizer() {
  53215. }
  53216. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  53217. // TODO: add an epsilon
  53218. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  53219. if (onSuccess) {
  53220. onSuccess();
  53221. }
  53222. return;
  53223. }
  53224. // Apply current level of optimizations
  53225. var allDone = true;
  53226. var noOptimizationApplied = true;
  53227. for (var index = 0; index < options.optimizations.length; index++) {
  53228. var optimization = options.optimizations[index];
  53229. if (optimization.priority === currentPriorityLevel) {
  53230. noOptimizationApplied = false;
  53231. allDone = allDone && optimization.apply(scene);
  53232. }
  53233. }
  53234. // If no optimization was applied, this is a failure :(
  53235. if (noOptimizationApplied) {
  53236. if (onFailure) {
  53237. onFailure();
  53238. }
  53239. return;
  53240. }
  53241. // If all optimizations were done, move to next level
  53242. if (allDone) {
  53243. currentPriorityLevel++;
  53244. }
  53245. // Let's the system running for a specific amount of time before checking FPS
  53246. scene.executeWhenReady(function () {
  53247. setTimeout(function () {
  53248. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  53249. }, options.trackerDuration);
  53250. });
  53251. };
  53252. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  53253. if (!options) {
  53254. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  53255. }
  53256. // Let's the system running for a specific amount of time before checking FPS
  53257. scene.executeWhenReady(function () {
  53258. setTimeout(function () {
  53259. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  53260. }, options.trackerDuration);
  53261. });
  53262. };
  53263. return SceneOptimizer;
  53264. }());
  53265. BABYLON.SceneOptimizer = SceneOptimizer;
  53266. })(BABYLON || (BABYLON = {}));
  53267. var BABYLON;
  53268. (function (BABYLON) {
  53269. var Internals;
  53270. (function (Internals) {
  53271. var MeshLODLevel = (function () {
  53272. function MeshLODLevel(distance, mesh) {
  53273. this.distance = distance;
  53274. this.mesh = mesh;
  53275. }
  53276. return MeshLODLevel;
  53277. }());
  53278. Internals.MeshLODLevel = MeshLODLevel;
  53279. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  53280. })(BABYLON || (BABYLON = {}));
  53281. var BABYLON;
  53282. (function (BABYLON) {
  53283. var RawTexture = (function (_super) {
  53284. __extends(RawTexture, _super);
  53285. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  53286. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53287. if (invertY === void 0) { invertY = false; }
  53288. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53289. _super.call(this, null, scene, !generateMipMaps, invertY);
  53290. this.format = format;
  53291. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  53292. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53293. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53294. }
  53295. RawTexture.prototype.update = function (data) {
  53296. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  53297. };
  53298. // Statics
  53299. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53300. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53301. if (invertY === void 0) { invertY = false; }
  53302. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53303. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  53304. };
  53305. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53306. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53307. if (invertY === void 0) { invertY = false; }
  53308. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53309. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  53310. };
  53311. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53312. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53313. if (invertY === void 0) { invertY = false; }
  53314. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53315. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  53316. };
  53317. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53318. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53319. if (invertY === void 0) { invertY = false; }
  53320. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53321. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  53322. };
  53323. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  53324. if (generateMipMaps === void 0) { generateMipMaps = true; }
  53325. if (invertY === void 0) { invertY = false; }
  53326. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53327. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  53328. };
  53329. return RawTexture;
  53330. }(BABYLON.Texture));
  53331. BABYLON.RawTexture = RawTexture;
  53332. })(BABYLON || (BABYLON = {}));
  53333. var BABYLON;
  53334. (function (BABYLON) {
  53335. var IndexedVector2 = (function (_super) {
  53336. __extends(IndexedVector2, _super);
  53337. function IndexedVector2(original, index) {
  53338. _super.call(this, original.x, original.y);
  53339. this.index = index;
  53340. }
  53341. return IndexedVector2;
  53342. }(BABYLON.Vector2));
  53343. var PolygonPoints = (function () {
  53344. function PolygonPoints() {
  53345. this.elements = new Array();
  53346. }
  53347. PolygonPoints.prototype.add = function (originalPoints) {
  53348. var _this = this;
  53349. var result = new Array();
  53350. originalPoints.forEach(function (point) {
  53351. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  53352. var newPoint = new IndexedVector2(point, _this.elements.length);
  53353. result.push(newPoint);
  53354. _this.elements.push(newPoint);
  53355. }
  53356. });
  53357. return result;
  53358. };
  53359. PolygonPoints.prototype.computeBounds = function () {
  53360. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53361. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  53362. this.elements.forEach(function (point) {
  53363. // x
  53364. if (point.x < lmin.x) {
  53365. lmin.x = point.x;
  53366. }
  53367. else if (point.x > lmax.x) {
  53368. lmax.x = point.x;
  53369. }
  53370. // y
  53371. if (point.y < lmin.y) {
  53372. lmin.y = point.y;
  53373. }
  53374. else if (point.y > lmax.y) {
  53375. lmax.y = point.y;
  53376. }
  53377. });
  53378. return {
  53379. min: lmin,
  53380. max: lmax,
  53381. width: lmax.x - lmin.x,
  53382. height: lmax.y - lmin.y
  53383. };
  53384. };
  53385. return PolygonPoints;
  53386. }());
  53387. var Polygon = (function () {
  53388. function Polygon() {
  53389. }
  53390. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  53391. return [
  53392. new BABYLON.Vector2(xmin, ymin),
  53393. new BABYLON.Vector2(xmax, ymin),
  53394. new BABYLON.Vector2(xmax, ymax),
  53395. new BABYLON.Vector2(xmin, ymax)
  53396. ];
  53397. };
  53398. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  53399. if (cx === void 0) { cx = 0; }
  53400. if (cy === void 0) { cy = 0; }
  53401. if (numberOfSides === void 0) { numberOfSides = 32; }
  53402. var result = new Array();
  53403. var angle = 0;
  53404. var increment = (Math.PI * 2) / numberOfSides;
  53405. for (var i = 0; i < numberOfSides; i++) {
  53406. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  53407. angle -= increment;
  53408. }
  53409. return result;
  53410. };
  53411. Polygon.Parse = function (input) {
  53412. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  53413. var i, result = [];
  53414. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  53415. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  53416. }
  53417. return result;
  53418. };
  53419. Polygon.StartingAt = function (x, y) {
  53420. return BABYLON.Path2.StartingAt(x, y);
  53421. };
  53422. return Polygon;
  53423. }());
  53424. BABYLON.Polygon = Polygon;
  53425. var PolygonMeshBuilder = (function () {
  53426. function PolygonMeshBuilder(name, contours, scene) {
  53427. this._points = new PolygonPoints();
  53428. this._outlinepoints = new PolygonPoints();
  53429. this._holes = [];
  53430. this._epoints = new Array();
  53431. this._eholes = new Array();
  53432. this._name = name;
  53433. this._scene = scene;
  53434. var points;
  53435. if (contours instanceof BABYLON.Path2) {
  53436. points = contours.getPoints();
  53437. }
  53438. else {
  53439. points = contours;
  53440. }
  53441. this._addToepoint(points);
  53442. this._points.add(points);
  53443. this._outlinepoints.add(points);
  53444. }
  53445. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  53446. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  53447. var p = points_1[_i];
  53448. this._epoints.push(p.x, p.y);
  53449. }
  53450. };
  53451. PolygonMeshBuilder.prototype.addHole = function (hole) {
  53452. this._points.add(hole);
  53453. var holepoints = new PolygonPoints();
  53454. holepoints.add(hole);
  53455. this._holes.push(holepoints);
  53456. this._eholes.push(this._epoints.length / 2);
  53457. this._addToepoint(hole);
  53458. return this;
  53459. };
  53460. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  53461. var _this = this;
  53462. if (updatable === void 0) { updatable = false; }
  53463. var result = new BABYLON.Mesh(this._name, this._scene);
  53464. var normals = [];
  53465. var positions = [];
  53466. var uvs = [];
  53467. var bounds = this._points.computeBounds();
  53468. this._points.elements.forEach(function (p) {
  53469. normals.push(0, 1.0, 0);
  53470. positions.push(p.x, 0, p.y);
  53471. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  53472. });
  53473. var indices = [];
  53474. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  53475. for (var i = 0; i < res.length; i++) {
  53476. indices.push(res[i]);
  53477. }
  53478. if (depth > 0) {
  53479. var positionscount = (positions.length / 3); //get the current pointcount
  53480. this._points.elements.forEach(function (p) {
  53481. normals.push(0, -1.0, 0);
  53482. positions.push(p.x, -depth, p.y);
  53483. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  53484. });
  53485. var totalCount = indices.length;
  53486. for (var i = 0; i < totalCount; i += 3) {
  53487. var i0 = indices[i + 0];
  53488. var i1 = indices[i + 1];
  53489. var i2 = indices[i + 2];
  53490. indices.push(i2 + positionscount);
  53491. indices.push(i1 + positionscount);
  53492. indices.push(i0 + positionscount);
  53493. }
  53494. //Add the sides
  53495. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  53496. this._holes.forEach(function (hole) {
  53497. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  53498. });
  53499. }
  53500. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  53501. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  53502. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  53503. result.setIndices(indices);
  53504. return result;
  53505. };
  53506. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  53507. var StartIndex = positions.length / 3;
  53508. var ulength = 0;
  53509. for (var i = 0; i < points.elements.length; i++) {
  53510. var p = points.elements[i];
  53511. var p1;
  53512. if ((i + 1) > points.elements.length - 1) {
  53513. p1 = points.elements[0];
  53514. }
  53515. else {
  53516. p1 = points.elements[i + 1];
  53517. }
  53518. positions.push(p.x, 0, p.y);
  53519. positions.push(p.x, -depth, p.y);
  53520. positions.push(p1.x, 0, p1.y);
  53521. positions.push(p1.x, -depth, p1.y);
  53522. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  53523. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  53524. var v3 = v2.subtract(v1);
  53525. var v4 = new BABYLON.Vector3(0, 1, 0);
  53526. var vn = BABYLON.Vector3.Cross(v3, v4);
  53527. vn = vn.normalize();
  53528. uvs.push(ulength / bounds.width, 0);
  53529. uvs.push(ulength / bounds.width, 1);
  53530. ulength += v3.length();
  53531. uvs.push((ulength / bounds.width), 0);
  53532. uvs.push((ulength / bounds.width), 1);
  53533. if (!flip) {
  53534. normals.push(-vn.x, -vn.y, -vn.z);
  53535. normals.push(-vn.x, -vn.y, -vn.z);
  53536. normals.push(-vn.x, -vn.y, -vn.z);
  53537. normals.push(-vn.x, -vn.y, -vn.z);
  53538. indices.push(StartIndex);
  53539. indices.push(StartIndex + 1);
  53540. indices.push(StartIndex + 2);
  53541. indices.push(StartIndex + 1);
  53542. indices.push(StartIndex + 3);
  53543. indices.push(StartIndex + 2);
  53544. }
  53545. else {
  53546. normals.push(vn.x, vn.y, vn.z);
  53547. normals.push(vn.x, vn.y, vn.z);
  53548. normals.push(vn.x, vn.y, vn.z);
  53549. normals.push(vn.x, vn.y, vn.z);
  53550. indices.push(StartIndex);
  53551. indices.push(StartIndex + 2);
  53552. indices.push(StartIndex + 1);
  53553. indices.push(StartIndex + 1);
  53554. indices.push(StartIndex + 2);
  53555. indices.push(StartIndex + 3);
  53556. }
  53557. StartIndex += 4;
  53558. }
  53559. ;
  53560. };
  53561. return PolygonMeshBuilder;
  53562. }());
  53563. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  53564. })(BABYLON || (BABYLON = {}));
  53565. var BABYLON;
  53566. (function (BABYLON) {
  53567. var Octree = (function () {
  53568. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  53569. if (maxDepth === void 0) { maxDepth = 2; }
  53570. this.maxDepth = maxDepth;
  53571. this.dynamicContent = new Array();
  53572. this._maxBlockCapacity = maxBlockCapacity || 64;
  53573. this._selectionContent = new BABYLON.SmartArray(1024);
  53574. this._creationFunc = creationFunc;
  53575. }
  53576. // Methods
  53577. Octree.prototype.update = function (worldMin, worldMax, entries) {
  53578. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  53579. };
  53580. Octree.prototype.addMesh = function (entry) {
  53581. for (var index = 0; index < this.blocks.length; index++) {
  53582. var block = this.blocks[index];
  53583. block.addEntry(entry);
  53584. }
  53585. };
  53586. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  53587. this._selectionContent.reset();
  53588. for (var index = 0; index < this.blocks.length; index++) {
  53589. var block = this.blocks[index];
  53590. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  53591. }
  53592. if (allowDuplicate) {
  53593. this._selectionContent.concat(this.dynamicContent);
  53594. }
  53595. else {
  53596. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53597. }
  53598. return this._selectionContent;
  53599. };
  53600. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  53601. this._selectionContent.reset();
  53602. for (var index = 0; index < this.blocks.length; index++) {
  53603. var block = this.blocks[index];
  53604. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  53605. }
  53606. if (allowDuplicate) {
  53607. this._selectionContent.concat(this.dynamicContent);
  53608. }
  53609. else {
  53610. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53611. }
  53612. return this._selectionContent;
  53613. };
  53614. Octree.prototype.intersectsRay = function (ray) {
  53615. this._selectionContent.reset();
  53616. for (var index = 0; index < this.blocks.length; index++) {
  53617. var block = this.blocks[index];
  53618. block.intersectsRay(ray, this._selectionContent);
  53619. }
  53620. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  53621. return this._selectionContent;
  53622. };
  53623. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  53624. target.blocks = new Array();
  53625. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  53626. // Segmenting space
  53627. for (var x = 0; x < 2; x++) {
  53628. for (var y = 0; y < 2; y++) {
  53629. for (var z = 0; z < 2; z++) {
  53630. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  53631. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  53632. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  53633. block.addEntries(entries);
  53634. target.blocks.push(block);
  53635. }
  53636. }
  53637. }
  53638. };
  53639. Octree.CreationFuncForMeshes = function (entry, block) {
  53640. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  53641. block.entries.push(entry);
  53642. }
  53643. };
  53644. Octree.CreationFuncForSubMeshes = function (entry, block) {
  53645. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  53646. block.entries.push(entry);
  53647. }
  53648. };
  53649. return Octree;
  53650. }());
  53651. BABYLON.Octree = Octree;
  53652. })(BABYLON || (BABYLON = {}));
  53653. var BABYLON;
  53654. (function (BABYLON) {
  53655. var OctreeBlock = (function () {
  53656. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  53657. this.entries = new Array();
  53658. this._boundingVectors = new Array();
  53659. this._capacity = capacity;
  53660. this._depth = depth;
  53661. this._maxDepth = maxDepth;
  53662. this._creationFunc = creationFunc;
  53663. this._minPoint = minPoint;
  53664. this._maxPoint = maxPoint;
  53665. this._boundingVectors.push(minPoint.clone());
  53666. this._boundingVectors.push(maxPoint.clone());
  53667. this._boundingVectors.push(minPoint.clone());
  53668. this._boundingVectors[2].x = maxPoint.x;
  53669. this._boundingVectors.push(minPoint.clone());
  53670. this._boundingVectors[3].y = maxPoint.y;
  53671. this._boundingVectors.push(minPoint.clone());
  53672. this._boundingVectors[4].z = maxPoint.z;
  53673. this._boundingVectors.push(maxPoint.clone());
  53674. this._boundingVectors[5].z = minPoint.z;
  53675. this._boundingVectors.push(maxPoint.clone());
  53676. this._boundingVectors[6].x = minPoint.x;
  53677. this._boundingVectors.push(maxPoint.clone());
  53678. this._boundingVectors[7].y = minPoint.y;
  53679. }
  53680. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  53681. // Property
  53682. get: function () {
  53683. return this._capacity;
  53684. },
  53685. enumerable: true,
  53686. configurable: true
  53687. });
  53688. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  53689. get: function () {
  53690. return this._minPoint;
  53691. },
  53692. enumerable: true,
  53693. configurable: true
  53694. });
  53695. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  53696. get: function () {
  53697. return this._maxPoint;
  53698. },
  53699. enumerable: true,
  53700. configurable: true
  53701. });
  53702. // Methods
  53703. OctreeBlock.prototype.addEntry = function (entry) {
  53704. if (this.blocks) {
  53705. for (var index = 0; index < this.blocks.length; index++) {
  53706. var block = this.blocks[index];
  53707. block.addEntry(entry);
  53708. }
  53709. return;
  53710. }
  53711. this._creationFunc(entry, this);
  53712. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  53713. this.createInnerBlocks();
  53714. }
  53715. };
  53716. OctreeBlock.prototype.addEntries = function (entries) {
  53717. for (var index = 0; index < entries.length; index++) {
  53718. var mesh = entries[index];
  53719. this.addEntry(mesh);
  53720. }
  53721. };
  53722. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  53723. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  53724. if (this.blocks) {
  53725. for (var index = 0; index < this.blocks.length; index++) {
  53726. var block = this.blocks[index];
  53727. block.select(frustumPlanes, selection, allowDuplicate);
  53728. }
  53729. return;
  53730. }
  53731. if (allowDuplicate) {
  53732. selection.concat(this.entries);
  53733. }
  53734. else {
  53735. selection.concatWithNoDuplicate(this.entries);
  53736. }
  53737. }
  53738. };
  53739. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  53740. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  53741. if (this.blocks) {
  53742. for (var index = 0; index < this.blocks.length; index++) {
  53743. var block = this.blocks[index];
  53744. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  53745. }
  53746. return;
  53747. }
  53748. if (allowDuplicate) {
  53749. selection.concat(this.entries);
  53750. }
  53751. else {
  53752. selection.concatWithNoDuplicate(this.entries);
  53753. }
  53754. }
  53755. };
  53756. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  53757. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  53758. if (this.blocks) {
  53759. for (var index = 0; index < this.blocks.length; index++) {
  53760. var block = this.blocks[index];
  53761. block.intersectsRay(ray, selection);
  53762. }
  53763. return;
  53764. }
  53765. selection.concatWithNoDuplicate(this.entries);
  53766. }
  53767. };
  53768. OctreeBlock.prototype.createInnerBlocks = function () {
  53769. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  53770. };
  53771. return OctreeBlock;
  53772. }());
  53773. BABYLON.OctreeBlock = OctreeBlock;
  53774. })(BABYLON || (BABYLON = {}));
  53775. var BABYLON;
  53776. (function (BABYLON) {
  53777. var BlurPostProcess = (function (_super) {
  53778. __extends(BlurPostProcess, _super);
  53779. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  53780. var _this = this;
  53781. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  53782. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  53783. this.direction = direction;
  53784. this.blurWidth = blurWidth;
  53785. this.onApplyObservable.add(function (effect) {
  53786. effect.setFloat2("screenSize", _this.width, _this.height);
  53787. effect.setVector2("direction", _this.direction);
  53788. effect.setFloat("blurWidth", _this.blurWidth);
  53789. });
  53790. }
  53791. return BlurPostProcess;
  53792. }(BABYLON.PostProcess));
  53793. BABYLON.BlurPostProcess = BlurPostProcess;
  53794. })(BABYLON || (BABYLON = {}));
  53795. var BABYLON;
  53796. (function (BABYLON) {
  53797. var RefractionPostProcess = (function (_super) {
  53798. __extends(RefractionPostProcess, _super);
  53799. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  53800. var _this = this;
  53801. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  53802. this.color = color;
  53803. this.depth = depth;
  53804. this.colorLevel = colorLevel;
  53805. this.onActivateObservable.add(function (cam) {
  53806. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  53807. });
  53808. this.onApplyObservable.add(function (effect) {
  53809. effect.setColor3("baseColor", _this.color);
  53810. effect.setFloat("depth", _this.depth);
  53811. effect.setFloat("colorLevel", _this.colorLevel);
  53812. effect.setTexture("refractionSampler", _this._refRexture);
  53813. });
  53814. }
  53815. // Methods
  53816. RefractionPostProcess.prototype.dispose = function (camera) {
  53817. if (this._refRexture) {
  53818. this._refRexture.dispose();
  53819. }
  53820. _super.prototype.dispose.call(this, camera);
  53821. };
  53822. return RefractionPostProcess;
  53823. }(BABYLON.PostProcess));
  53824. BABYLON.RefractionPostProcess = RefractionPostProcess;
  53825. })(BABYLON || (BABYLON = {}));
  53826. var BABYLON;
  53827. (function (BABYLON) {
  53828. var BlackAndWhitePostProcess = (function (_super) {
  53829. __extends(BlackAndWhitePostProcess, _super);
  53830. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  53831. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  53832. }
  53833. return BlackAndWhitePostProcess;
  53834. }(BABYLON.PostProcess));
  53835. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  53836. })(BABYLON || (BABYLON = {}));
  53837. var BABYLON;
  53838. (function (BABYLON) {
  53839. var ConvolutionPostProcess = (function (_super) {
  53840. __extends(ConvolutionPostProcess, _super);
  53841. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  53842. var _this = this;
  53843. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  53844. this.kernel = kernel;
  53845. this.onApply = function (effect) {
  53846. effect.setFloat2("screenSize", _this.width, _this.height);
  53847. effect.setArray("kernel", _this.kernel);
  53848. };
  53849. }
  53850. // Statics
  53851. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  53852. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  53853. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  53854. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  53855. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  53856. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  53857. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  53858. return ConvolutionPostProcess;
  53859. }(BABYLON.PostProcess));
  53860. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  53861. })(BABYLON || (BABYLON = {}));
  53862. var BABYLON;
  53863. (function (BABYLON) {
  53864. var FilterPostProcess = (function (_super) {
  53865. __extends(FilterPostProcess, _super);
  53866. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  53867. var _this = this;
  53868. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  53869. this.kernelMatrix = kernelMatrix;
  53870. this.onApply = function (effect) {
  53871. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  53872. };
  53873. }
  53874. return FilterPostProcess;
  53875. }(BABYLON.PostProcess));
  53876. BABYLON.FilterPostProcess = FilterPostProcess;
  53877. })(BABYLON || (BABYLON = {}));
  53878. var BABYLON;
  53879. (function (BABYLON) {
  53880. var FxaaPostProcess = (function (_super) {
  53881. __extends(FxaaPostProcess, _super);
  53882. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  53883. var _this = this;
  53884. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  53885. this.onSizeChangedObservable.add(function () {
  53886. _this.texelWidth = 1.0 / _this.width;
  53887. _this.texelHeight = 1.0 / _this.height;
  53888. });
  53889. this.onApplyObservable.add(function (effect) {
  53890. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  53891. });
  53892. }
  53893. return FxaaPostProcess;
  53894. }(BABYLON.PostProcess));
  53895. BABYLON.FxaaPostProcess = FxaaPostProcess;
  53896. })(BABYLON || (BABYLON = {}));
  53897. var BABYLON;
  53898. (function (BABYLON) {
  53899. var StereoscopicInterlacePostProcess = (function (_super) {
  53900. __extends(StereoscopicInterlacePostProcess, _super);
  53901. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  53902. var _this = this;
  53903. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  53904. this._passedProcess = rigCameras[0]._rigPostProcess;
  53905. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  53906. this.onSizeChangedObservable.add(function () {
  53907. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  53908. });
  53909. this.onApplyObservable.add(function (effect) {
  53910. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  53911. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  53912. });
  53913. }
  53914. return StereoscopicInterlacePostProcess;
  53915. }(BABYLON.PostProcess));
  53916. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  53917. })(BABYLON || (BABYLON = {}));
  53918. var BABYLON;
  53919. (function (BABYLON) {
  53920. var LensFlare = (function () {
  53921. function LensFlare(size, position, color, imgUrl, system) {
  53922. this.size = size;
  53923. this.position = position;
  53924. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  53925. this.dispose = function () {
  53926. if (this.texture) {
  53927. this.texture.dispose();
  53928. }
  53929. // Remove from scene
  53930. var index = this._system.lensFlares.indexOf(this);
  53931. this._system.lensFlares.splice(index, 1);
  53932. };
  53933. this.color = color || new BABYLON.Color3(1, 1, 1);
  53934. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  53935. this._system = system;
  53936. system.lensFlares.push(this);
  53937. }
  53938. return LensFlare;
  53939. }());
  53940. BABYLON.LensFlare = LensFlare;
  53941. })(BABYLON || (BABYLON = {}));
  53942. var BABYLON;
  53943. (function (BABYLON) {
  53944. var LensFlareSystem = (function () {
  53945. function LensFlareSystem(name, emitter, scene) {
  53946. this.name = name;
  53947. this.lensFlares = new Array();
  53948. this.borderLimit = 300;
  53949. this.layerMask = 0x0FFFFFFF;
  53950. this._vertexBuffers = {};
  53951. this._isEnabled = true;
  53952. this._scene = scene;
  53953. this._emitter = emitter;
  53954. this.id = name;
  53955. scene.lensFlareSystems.push(this);
  53956. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  53957. var engine = scene.getEngine();
  53958. // VBO
  53959. var vertices = [];
  53960. vertices.push(1, 1);
  53961. vertices.push(-1, 1);
  53962. vertices.push(-1, -1);
  53963. vertices.push(1, -1);
  53964. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  53965. // Indices
  53966. var indices = [];
  53967. indices.push(0);
  53968. indices.push(1);
  53969. indices.push(2);
  53970. indices.push(0);
  53971. indices.push(2);
  53972. indices.push(3);
  53973. this._indexBuffer = engine.createIndexBuffer(indices);
  53974. // Effects
  53975. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  53976. }
  53977. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  53978. get: function () {
  53979. return this._isEnabled;
  53980. },
  53981. set: function (value) {
  53982. this._isEnabled = value;
  53983. },
  53984. enumerable: true,
  53985. configurable: true
  53986. });
  53987. LensFlareSystem.prototype.getScene = function () {
  53988. return this._scene;
  53989. };
  53990. LensFlareSystem.prototype.getEmitter = function () {
  53991. return this._emitter;
  53992. };
  53993. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  53994. this._emitter = newEmitter;
  53995. };
  53996. LensFlareSystem.prototype.getEmitterPosition = function () {
  53997. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  53998. };
  53999. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  54000. var position = this.getEmitterPosition();
  54001. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  54002. this._positionX = position.x;
  54003. this._positionY = position.y;
  54004. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  54005. if (position.z > 0) {
  54006. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  54007. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  54008. return true;
  54009. }
  54010. }
  54011. return false;
  54012. };
  54013. LensFlareSystem.prototype._isVisible = function () {
  54014. if (!this._isEnabled) {
  54015. return false;
  54016. }
  54017. var emitterPosition = this.getEmitterPosition();
  54018. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  54019. var distance = direction.length();
  54020. direction.normalize();
  54021. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  54022. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  54023. return !pickInfo.hit || pickInfo.distance > distance;
  54024. };
  54025. LensFlareSystem.prototype.render = function () {
  54026. if (!this._effect.isReady())
  54027. return false;
  54028. var engine = this._scene.getEngine();
  54029. var viewport = this._scene.activeCamera.viewport;
  54030. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  54031. // Position
  54032. if (!this.computeEffectivePosition(globalViewport)) {
  54033. return false;
  54034. }
  54035. // Visibility
  54036. if (!this._isVisible()) {
  54037. return false;
  54038. }
  54039. // Intensity
  54040. var awayX;
  54041. var awayY;
  54042. if (this._positionX < this.borderLimit + globalViewport.x) {
  54043. awayX = this.borderLimit + globalViewport.x - this._positionX;
  54044. }
  54045. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  54046. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  54047. }
  54048. else {
  54049. awayX = 0;
  54050. }
  54051. if (this._positionY < this.borderLimit + globalViewport.y) {
  54052. awayY = this.borderLimit + globalViewport.y - this._positionY;
  54053. }
  54054. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  54055. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  54056. }
  54057. else {
  54058. awayY = 0;
  54059. }
  54060. var away = (awayX > awayY) ? awayX : awayY;
  54061. if (away > this.borderLimit) {
  54062. away = this.borderLimit;
  54063. }
  54064. var intensity = 1.0 - (away / this.borderLimit);
  54065. if (intensity < 0) {
  54066. return false;
  54067. }
  54068. if (intensity > 1.0) {
  54069. intensity = 1.0;
  54070. }
  54071. // Position
  54072. var centerX = globalViewport.x + globalViewport.width / 2;
  54073. var centerY = globalViewport.y + globalViewport.height / 2;
  54074. var distX = centerX - this._positionX;
  54075. var distY = centerY - this._positionY;
  54076. // Effects
  54077. engine.enableEffect(this._effect);
  54078. engine.setState(false);
  54079. engine.setDepthBuffer(false);
  54080. // VBOs
  54081. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  54082. // Flares
  54083. for (var index = 0; index < this.lensFlares.length; index++) {
  54084. var flare = this.lensFlares[index];
  54085. engine.setAlphaMode(flare.alphaMode);
  54086. var x = centerX - (distX * flare.position);
  54087. var y = centerY - (distY * flare.position);
  54088. var cw = flare.size;
  54089. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  54090. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  54091. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  54092. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  54093. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  54094. // Texture
  54095. this._effect.setTexture("textureSampler", flare.texture);
  54096. // Color
  54097. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  54098. // Draw order
  54099. engine.draw(true, 0, 6);
  54100. }
  54101. engine.setDepthBuffer(true);
  54102. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54103. return true;
  54104. };
  54105. LensFlareSystem.prototype.dispose = function () {
  54106. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  54107. if (vertexBuffer) {
  54108. vertexBuffer.dispose();
  54109. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  54110. }
  54111. if (this._indexBuffer) {
  54112. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54113. this._indexBuffer = null;
  54114. }
  54115. while (this.lensFlares.length) {
  54116. this.lensFlares[0].dispose();
  54117. }
  54118. // Remove from scene
  54119. var index = this._scene.lensFlareSystems.indexOf(this);
  54120. this._scene.lensFlareSystems.splice(index, 1);
  54121. };
  54122. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  54123. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  54124. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  54125. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  54126. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  54127. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  54128. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  54129. var parsedFlare = parsedLensFlareSystem.flares[index];
  54130. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  54131. }
  54132. return lensFlareSystem;
  54133. };
  54134. LensFlareSystem.prototype.serialize = function () {
  54135. var serializationObject = {};
  54136. serializationObject.id = this.id;
  54137. serializationObject.name = this.name;
  54138. serializationObject.emitterId = this.getEmitter().id;
  54139. serializationObject.borderLimit = this.borderLimit;
  54140. serializationObject.flares = [];
  54141. for (var index = 0; index < this.lensFlares.length; index++) {
  54142. var flare = this.lensFlares[index];
  54143. serializationObject.flares.push({
  54144. size: flare.size,
  54145. position: flare.position,
  54146. color: flare.color.asArray(),
  54147. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  54148. });
  54149. }
  54150. return serializationObject;
  54151. };
  54152. return LensFlareSystem;
  54153. }());
  54154. BABYLON.LensFlareSystem = LensFlareSystem;
  54155. })(BABYLON || (BABYLON = {}));
  54156. var BABYLON;
  54157. (function (BABYLON) {
  54158. // We're mainly based on the logic defined into the FreeCamera code
  54159. var DeviceOrientationCamera = (function (_super) {
  54160. __extends(DeviceOrientationCamera, _super);
  54161. function DeviceOrientationCamera(name, position, scene) {
  54162. _super.call(this, name, position, scene);
  54163. this.inputs.addDeviceOrientation();
  54164. }
  54165. DeviceOrientationCamera.prototype.getTypeName = function () {
  54166. return "DeviceOrientationCamera";
  54167. };
  54168. DeviceOrientationCamera.prototype._checkInputs = function () {
  54169. _super.prototype._checkInputs.call(this);
  54170. if (this._initialQuaternion) {
  54171. this._quaternionCache.copyFrom(this.rotationQuaternion);
  54172. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  54173. }
  54174. };
  54175. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  54176. var _this = this;
  54177. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  54178. //can only work if this camera has a rotation quaternion already.
  54179. if (!this.rotationQuaternion)
  54180. return;
  54181. if (!this._initialQuaternion) {
  54182. this._initialQuaternion = new BABYLON.Quaternion();
  54183. }
  54184. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  54185. ['x', 'y', 'z'].forEach(function (axisName) {
  54186. if (!axis[axisName]) {
  54187. _this._initialQuaternion[axisName] = 0;
  54188. }
  54189. else {
  54190. _this._initialQuaternion[axisName] *= -1;
  54191. }
  54192. });
  54193. this._initialQuaternion.normalize();
  54194. };
  54195. return DeviceOrientationCamera;
  54196. }(BABYLON.FreeCamera));
  54197. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  54198. })(BABYLON || (BABYLON = {}));
  54199. var BABYLON;
  54200. (function (BABYLON) {
  54201. var VRDeviceOrientationFreeCamera = (function (_super) {
  54202. __extends(VRDeviceOrientationFreeCamera, _super);
  54203. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  54204. if (compensateDistortion === void 0) { compensateDistortion = true; }
  54205. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  54206. _super.call(this, name, position, scene);
  54207. vrCameraMetrics.compensateDistortion = compensateDistortion;
  54208. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  54209. }
  54210. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  54211. return "VRDeviceOrientationFreeCamera";
  54212. };
  54213. return VRDeviceOrientationFreeCamera;
  54214. }(BABYLON.DeviceOrientationCamera));
  54215. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  54216. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  54217. __extends(VRDeviceOrientationArcRotateCamera, _super);
  54218. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion) {
  54219. if (compensateDistortion === void 0) { compensateDistortion = true; }
  54220. _super.call(this, name, alpha, beta, radius, target, scene);
  54221. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  54222. metrics.compensateDistortion = compensateDistortion;
  54223. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  54224. this.inputs.addVRDeviceOrientation();
  54225. }
  54226. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  54227. return "VRDeviceOrientationArcRotateCamera";
  54228. };
  54229. return VRDeviceOrientationArcRotateCamera;
  54230. }(BABYLON.ArcRotateCamera));
  54231. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  54232. })(BABYLON || (BABYLON = {}));
  54233. var BABYLON;
  54234. (function (BABYLON) {
  54235. // We're mainly based on the logic defined into the FreeCamera code
  54236. var UniversalCamera = (function (_super) {
  54237. __extends(UniversalCamera, _super);
  54238. //-- end properties for backward compatibility for inputs
  54239. function UniversalCamera(name, position, scene) {
  54240. _super.call(this, name, position, scene);
  54241. this.inputs.addGamepad();
  54242. }
  54243. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  54244. //-- Begin properties for backward compatibility for inputs
  54245. get: function () {
  54246. var gamepad = this.inputs.attached["gamepad"];
  54247. if (gamepad)
  54248. return gamepad.gamepadAngularSensibility;
  54249. },
  54250. set: function (value) {
  54251. var gamepad = this.inputs.attached["gamepad"];
  54252. if (gamepad)
  54253. gamepad.gamepadAngularSensibility = value;
  54254. },
  54255. enumerable: true,
  54256. configurable: true
  54257. });
  54258. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  54259. get: function () {
  54260. var gamepad = this.inputs.attached["gamepad"];
  54261. if (gamepad)
  54262. return gamepad.gamepadMoveSensibility;
  54263. },
  54264. set: function (value) {
  54265. var gamepad = this.inputs.attached["gamepad"];
  54266. if (gamepad)
  54267. gamepad.gamepadMoveSensibility = value;
  54268. },
  54269. enumerable: true,
  54270. configurable: true
  54271. });
  54272. UniversalCamera.prototype.getTypeName = function () {
  54273. return "UniversalCamera";
  54274. };
  54275. return UniversalCamera;
  54276. }(BABYLON.TouchCamera));
  54277. BABYLON.UniversalCamera = UniversalCamera;
  54278. })(BABYLON || (BABYLON = {}));
  54279. var BABYLON;
  54280. (function (BABYLON) {
  54281. var Gamepads = (function () {
  54282. function Gamepads(ongamedpadconnected) {
  54283. var _this = this;
  54284. this.babylonGamepads = [];
  54285. this.oneGamepadConnected = false;
  54286. this.isMonitoring = false;
  54287. this.gamepadEventSupported = 'GamepadEvent' in window;
  54288. this.gamepadSupportAvailable = (navigator.getGamepads ||
  54289. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  54290. this._callbackGamepadConnected = ongamedpadconnected;
  54291. if (this.gamepadSupportAvailable) {
  54292. // Checking if the gamepad connected event is supported (like in Firefox)
  54293. if (this.gamepadEventSupported) {
  54294. this._onGamepadConnectedEvent = function (evt) {
  54295. _this._onGamepadConnected(evt);
  54296. };
  54297. this._onGamepadDisonnectedEvent = function (evt) {
  54298. _this._onGamepadDisconnected(evt);
  54299. };
  54300. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54301. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  54302. }
  54303. else {
  54304. this._startMonitoringGamepads();
  54305. }
  54306. }
  54307. }
  54308. Gamepads.prototype.dispose = function () {
  54309. if (Gamepads.gamepadDOMInfo) {
  54310. document.body.removeChild(Gamepads.gamepadDOMInfo);
  54311. }
  54312. if (this._onGamepadConnectedEvent) {
  54313. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  54314. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  54315. this._onGamepadConnectedEvent = null;
  54316. this._onGamepadDisonnectedEvent = null;
  54317. }
  54318. };
  54319. Gamepads.prototype._onGamepadConnected = function (evt) {
  54320. var newGamepad = this._addNewGamepad(evt.gamepad);
  54321. if (this._callbackGamepadConnected)
  54322. this._callbackGamepadConnected(newGamepad);
  54323. this._startMonitoringGamepads();
  54324. };
  54325. Gamepads.prototype._addNewGamepad = function (gamepad) {
  54326. if (!this.oneGamepadConnected) {
  54327. this.oneGamepadConnected = true;
  54328. if (Gamepads.gamepadDOMInfo) {
  54329. document.body.removeChild(Gamepads.gamepadDOMInfo);
  54330. Gamepads.gamepadDOMInfo = null;
  54331. }
  54332. }
  54333. var newGamepad;
  54334. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  54335. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  54336. }
  54337. else {
  54338. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  54339. }
  54340. this.babylonGamepads.push(newGamepad);
  54341. return newGamepad;
  54342. };
  54343. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  54344. // Remove the gamepad from the list of gamepads to monitor.
  54345. for (var i in this.babylonGamepads) {
  54346. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  54347. this.babylonGamepads.splice(+i, 1);
  54348. break;
  54349. }
  54350. }
  54351. // If no gamepads are left, stop the polling loop.
  54352. if (this.babylonGamepads.length == 0) {
  54353. this._stopMonitoringGamepads();
  54354. }
  54355. };
  54356. Gamepads.prototype._startMonitoringGamepads = function () {
  54357. if (!this.isMonitoring) {
  54358. this.isMonitoring = true;
  54359. this._checkGamepadsStatus();
  54360. }
  54361. };
  54362. Gamepads.prototype._stopMonitoringGamepads = function () {
  54363. this.isMonitoring = false;
  54364. };
  54365. Gamepads.prototype._checkGamepadsStatus = function () {
  54366. var _this = this;
  54367. // updating gamepad objects
  54368. this._updateGamepadObjects();
  54369. for (var i in this.babylonGamepads) {
  54370. this.babylonGamepads[i].update();
  54371. }
  54372. if (this.isMonitoring) {
  54373. if (window.requestAnimationFrame) {
  54374. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54375. }
  54376. else if (window.mozRequestAnimationFrame) {
  54377. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54378. }
  54379. else if (window.webkitRequestAnimationFrame) {
  54380. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  54381. }
  54382. }
  54383. };
  54384. // This function is called only on Chrome, which does not yet support
  54385. // connection/disconnection events, but requires you to monitor
  54386. // an array for changes.
  54387. Gamepads.prototype._updateGamepadObjects = function () {
  54388. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  54389. for (var i = 0; i < gamepads.length; i++) {
  54390. if (gamepads[i]) {
  54391. if (!(gamepads[i].index in this.babylonGamepads)) {
  54392. var newGamepad = this._addNewGamepad(gamepads[i]);
  54393. if (this._callbackGamepadConnected) {
  54394. this._callbackGamepadConnected(newGamepad);
  54395. }
  54396. }
  54397. else {
  54398. this.babylonGamepads[i].browserGamepad = gamepads[i];
  54399. }
  54400. }
  54401. }
  54402. };
  54403. return Gamepads;
  54404. }());
  54405. BABYLON.Gamepads = Gamepads;
  54406. var StickValues = (function () {
  54407. function StickValues(x, y) {
  54408. this.x = x;
  54409. this.y = y;
  54410. }
  54411. return StickValues;
  54412. }());
  54413. BABYLON.StickValues = StickValues;
  54414. var Gamepad = (function () {
  54415. function Gamepad(id, index, browserGamepad) {
  54416. this.id = id;
  54417. this.index = index;
  54418. this.browserGamepad = browserGamepad;
  54419. if (this.browserGamepad.axes.length >= 2) {
  54420. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  54421. }
  54422. if (this.browserGamepad.axes.length >= 4) {
  54423. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  54424. }
  54425. }
  54426. Gamepad.prototype.onleftstickchanged = function (callback) {
  54427. this._onleftstickchanged = callback;
  54428. };
  54429. Gamepad.prototype.onrightstickchanged = function (callback) {
  54430. this._onrightstickchanged = callback;
  54431. };
  54432. Object.defineProperty(Gamepad.prototype, "leftStick", {
  54433. get: function () {
  54434. return this._leftStick;
  54435. },
  54436. set: function (newValues) {
  54437. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  54438. this._onleftstickchanged(newValues);
  54439. }
  54440. this._leftStick = newValues;
  54441. },
  54442. enumerable: true,
  54443. configurable: true
  54444. });
  54445. Object.defineProperty(Gamepad.prototype, "rightStick", {
  54446. get: function () {
  54447. return this._rightStick;
  54448. },
  54449. set: function (newValues) {
  54450. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  54451. this._onrightstickchanged(newValues);
  54452. }
  54453. this._rightStick = newValues;
  54454. },
  54455. enumerable: true,
  54456. configurable: true
  54457. });
  54458. Gamepad.prototype.update = function () {
  54459. if (this._leftStick) {
  54460. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  54461. }
  54462. if (this._rightStick) {
  54463. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  54464. }
  54465. };
  54466. return Gamepad;
  54467. }());
  54468. BABYLON.Gamepad = Gamepad;
  54469. var GenericPad = (function (_super) {
  54470. __extends(GenericPad, _super);
  54471. function GenericPad(id, index, gamepad) {
  54472. _super.call(this, id, index, gamepad);
  54473. this.id = id;
  54474. this.index = index;
  54475. this.gamepad = gamepad;
  54476. this._buttons = new Array(gamepad.buttons.length);
  54477. }
  54478. GenericPad.prototype.onbuttondown = function (callback) {
  54479. this._onbuttondown = callback;
  54480. };
  54481. GenericPad.prototype.onbuttonup = function (callback) {
  54482. this._onbuttonup = callback;
  54483. };
  54484. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  54485. if (newValue !== currentValue) {
  54486. if (this._onbuttondown && newValue === 1) {
  54487. this._onbuttondown(buttonIndex);
  54488. }
  54489. if (this._onbuttonup && newValue === 0) {
  54490. this._onbuttonup(buttonIndex);
  54491. }
  54492. }
  54493. return newValue;
  54494. };
  54495. GenericPad.prototype.update = function () {
  54496. _super.prototype.update.call(this);
  54497. for (var index = 0; index < this._buttons.length; index++) {
  54498. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  54499. }
  54500. };
  54501. return GenericPad;
  54502. }(Gamepad));
  54503. BABYLON.GenericPad = GenericPad;
  54504. (function (Xbox360Button) {
  54505. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  54506. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  54507. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  54508. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  54509. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  54510. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  54511. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  54512. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  54513. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  54514. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  54515. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  54516. var Xbox360Button = BABYLON.Xbox360Button;
  54517. (function (Xbox360Dpad) {
  54518. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  54519. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  54520. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  54521. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  54522. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  54523. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  54524. var Xbox360Pad = (function (_super) {
  54525. __extends(Xbox360Pad, _super);
  54526. function Xbox360Pad() {
  54527. _super.apply(this, arguments);
  54528. this._leftTrigger = 0;
  54529. this._rightTrigger = 0;
  54530. this._buttonA = 0;
  54531. this._buttonB = 0;
  54532. this._buttonX = 0;
  54533. this._buttonY = 0;
  54534. this._buttonBack = 0;
  54535. this._buttonStart = 0;
  54536. this._buttonLB = 0;
  54537. this._buttonRB = 0;
  54538. this._buttonLeftStick = 0;
  54539. this._buttonRightStick = 0;
  54540. this._dPadUp = 0;
  54541. this._dPadDown = 0;
  54542. this._dPadLeft = 0;
  54543. this._dPadRight = 0;
  54544. }
  54545. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  54546. this._onlefttriggerchanged = callback;
  54547. };
  54548. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  54549. this._onrighttriggerchanged = callback;
  54550. };
  54551. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  54552. get: function () {
  54553. return this._leftTrigger;
  54554. },
  54555. set: function (newValue) {
  54556. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  54557. this._onlefttriggerchanged(newValue);
  54558. }
  54559. this._leftTrigger = newValue;
  54560. },
  54561. enumerable: true,
  54562. configurable: true
  54563. });
  54564. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  54565. get: function () {
  54566. return this._rightTrigger;
  54567. },
  54568. set: function (newValue) {
  54569. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  54570. this._onrighttriggerchanged(newValue);
  54571. }
  54572. this._rightTrigger = newValue;
  54573. },
  54574. enumerable: true,
  54575. configurable: true
  54576. });
  54577. Xbox360Pad.prototype.onbuttondown = function (callback) {
  54578. this._onbuttondown = callback;
  54579. };
  54580. Xbox360Pad.prototype.onbuttonup = function (callback) {
  54581. this._onbuttonup = callback;
  54582. };
  54583. Xbox360Pad.prototype.ondpaddown = function (callback) {
  54584. this._ondpaddown = callback;
  54585. };
  54586. Xbox360Pad.prototype.ondpadup = function (callback) {
  54587. this._ondpadup = callback;
  54588. };
  54589. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  54590. if (newValue !== currentValue) {
  54591. if (this._onbuttondown && newValue === 1) {
  54592. this._onbuttondown(buttonType);
  54593. }
  54594. if (this._onbuttonup && newValue === 0) {
  54595. this._onbuttonup(buttonType);
  54596. }
  54597. }
  54598. return newValue;
  54599. };
  54600. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  54601. if (newValue !== currentValue) {
  54602. if (this._ondpaddown && newValue === 1) {
  54603. this._ondpaddown(buttonType);
  54604. }
  54605. if (this._ondpadup && newValue === 0) {
  54606. this._ondpadup(buttonType);
  54607. }
  54608. }
  54609. return newValue;
  54610. };
  54611. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  54612. get: function () {
  54613. return this._buttonA;
  54614. },
  54615. set: function (value) {
  54616. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  54617. },
  54618. enumerable: true,
  54619. configurable: true
  54620. });
  54621. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  54622. get: function () {
  54623. return this._buttonB;
  54624. },
  54625. set: function (value) {
  54626. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  54627. },
  54628. enumerable: true,
  54629. configurable: true
  54630. });
  54631. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  54632. get: function () {
  54633. return this._buttonX;
  54634. },
  54635. set: function (value) {
  54636. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  54637. },
  54638. enumerable: true,
  54639. configurable: true
  54640. });
  54641. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  54642. get: function () {
  54643. return this._buttonY;
  54644. },
  54645. set: function (value) {
  54646. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  54647. },
  54648. enumerable: true,
  54649. configurable: true
  54650. });
  54651. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  54652. get: function () {
  54653. return this._buttonStart;
  54654. },
  54655. set: function (value) {
  54656. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  54657. },
  54658. enumerable: true,
  54659. configurable: true
  54660. });
  54661. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  54662. get: function () {
  54663. return this._buttonBack;
  54664. },
  54665. set: function (value) {
  54666. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  54667. },
  54668. enumerable: true,
  54669. configurable: true
  54670. });
  54671. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  54672. get: function () {
  54673. return this._buttonLB;
  54674. },
  54675. set: function (value) {
  54676. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  54677. },
  54678. enumerable: true,
  54679. configurable: true
  54680. });
  54681. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  54682. get: function () {
  54683. return this._buttonRB;
  54684. },
  54685. set: function (value) {
  54686. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  54687. },
  54688. enumerable: true,
  54689. configurable: true
  54690. });
  54691. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  54692. get: function () {
  54693. return this._buttonLeftStick;
  54694. },
  54695. set: function (value) {
  54696. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  54697. },
  54698. enumerable: true,
  54699. configurable: true
  54700. });
  54701. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  54702. get: function () {
  54703. return this._buttonRightStick;
  54704. },
  54705. set: function (value) {
  54706. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  54707. },
  54708. enumerable: true,
  54709. configurable: true
  54710. });
  54711. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  54712. get: function () {
  54713. return this._dPadUp;
  54714. },
  54715. set: function (value) {
  54716. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  54717. },
  54718. enumerable: true,
  54719. configurable: true
  54720. });
  54721. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  54722. get: function () {
  54723. return this._dPadDown;
  54724. },
  54725. set: function (value) {
  54726. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  54727. },
  54728. enumerable: true,
  54729. configurable: true
  54730. });
  54731. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  54732. get: function () {
  54733. return this._dPadLeft;
  54734. },
  54735. set: function (value) {
  54736. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  54737. },
  54738. enumerable: true,
  54739. configurable: true
  54740. });
  54741. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  54742. get: function () {
  54743. return this._dPadRight;
  54744. },
  54745. set: function (value) {
  54746. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  54747. },
  54748. enumerable: true,
  54749. configurable: true
  54750. });
  54751. Xbox360Pad.prototype.update = function () {
  54752. _super.prototype.update.call(this);
  54753. this.buttonA = this.browserGamepad.buttons[0].value;
  54754. this.buttonB = this.browserGamepad.buttons[1].value;
  54755. this.buttonX = this.browserGamepad.buttons[2].value;
  54756. this.buttonY = this.browserGamepad.buttons[3].value;
  54757. this.buttonLB = this.browserGamepad.buttons[4].value;
  54758. this.buttonRB = this.browserGamepad.buttons[5].value;
  54759. this.leftTrigger = this.browserGamepad.buttons[6].value;
  54760. this.rightTrigger = this.browserGamepad.buttons[7].value;
  54761. this.buttonBack = this.browserGamepad.buttons[8].value;
  54762. this.buttonStart = this.browserGamepad.buttons[9].value;
  54763. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  54764. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  54765. this.dPadUp = this.browserGamepad.buttons[12].value;
  54766. this.dPadDown = this.browserGamepad.buttons[13].value;
  54767. this.dPadLeft = this.browserGamepad.buttons[14].value;
  54768. this.dPadRight = this.browserGamepad.buttons[15].value;
  54769. };
  54770. return Xbox360Pad;
  54771. }(Gamepad));
  54772. BABYLON.Xbox360Pad = Xbox360Pad;
  54773. })(BABYLON || (BABYLON = {}));
  54774. var BABYLON;
  54775. (function (BABYLON) {
  54776. // We're mainly based on the logic defined into the FreeCamera code
  54777. var GamepadCamera = (function (_super) {
  54778. __extends(GamepadCamera, _super);
  54779. //-- end properties for backward compatibility for inputs
  54780. function GamepadCamera(name, position, scene) {
  54781. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  54782. _super.call(this, name, position, scene);
  54783. }
  54784. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  54785. //-- Begin properties for backward compatibility for inputs
  54786. get: function () {
  54787. var gamepad = this.inputs.attached["gamepad"];
  54788. if (gamepad)
  54789. return gamepad.gamepadAngularSensibility;
  54790. },
  54791. set: function (value) {
  54792. var gamepad = this.inputs.attached["gamepad"];
  54793. if (gamepad)
  54794. gamepad.gamepadAngularSensibility = value;
  54795. },
  54796. enumerable: true,
  54797. configurable: true
  54798. });
  54799. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  54800. get: function () {
  54801. var gamepad = this.inputs.attached["gamepad"];
  54802. if (gamepad)
  54803. return gamepad.gamepadMoveSensibility;
  54804. },
  54805. set: function (value) {
  54806. var gamepad = this.inputs.attached["gamepad"];
  54807. if (gamepad)
  54808. gamepad.gamepadMoveSensibility = value;
  54809. },
  54810. enumerable: true,
  54811. configurable: true
  54812. });
  54813. GamepadCamera.prototype.getTypeName = function () {
  54814. return "GamepadCamera";
  54815. };
  54816. return GamepadCamera;
  54817. }(BABYLON.UniversalCamera));
  54818. BABYLON.GamepadCamera = GamepadCamera;
  54819. })(BABYLON || (BABYLON = {}));
  54820. var BABYLON;
  54821. (function (BABYLON) {
  54822. var Analyser = (function () {
  54823. function Analyser(scene) {
  54824. this.SMOOTHING = 0.75;
  54825. this.FFT_SIZE = 512;
  54826. this.BARGRAPHAMPLITUDE = 256;
  54827. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  54828. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  54829. this._scene = scene;
  54830. this._audioEngine = BABYLON.Engine.audioEngine;
  54831. if (this._audioEngine.canUseWebAudio) {
  54832. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  54833. this._webAudioAnalyser.minDecibels = -140;
  54834. this._webAudioAnalyser.maxDecibels = 0;
  54835. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54836. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  54837. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  54838. }
  54839. }
  54840. Analyser.prototype.getFrequencyBinCount = function () {
  54841. if (this._audioEngine.canUseWebAudio) {
  54842. return this._webAudioAnalyser.frequencyBinCount;
  54843. }
  54844. else {
  54845. return 0;
  54846. }
  54847. };
  54848. Analyser.prototype.getByteFrequencyData = function () {
  54849. if (this._audioEngine.canUseWebAudio) {
  54850. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54851. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54852. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  54853. }
  54854. return this._byteFreqs;
  54855. };
  54856. Analyser.prototype.getByteTimeDomainData = function () {
  54857. if (this._audioEngine.canUseWebAudio) {
  54858. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54859. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54860. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  54861. }
  54862. return this._byteTime;
  54863. };
  54864. Analyser.prototype.getFloatFrequencyData = function () {
  54865. if (this._audioEngine.canUseWebAudio) {
  54866. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  54867. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  54868. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  54869. }
  54870. return this._floatFreqs;
  54871. };
  54872. Analyser.prototype.drawDebugCanvas = function () {
  54873. var _this = this;
  54874. if (this._audioEngine.canUseWebAudio) {
  54875. if (!this._debugCanvas) {
  54876. this._debugCanvas = document.createElement("canvas");
  54877. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  54878. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  54879. this._debugCanvas.style.position = "absolute";
  54880. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  54881. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  54882. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  54883. document.body.appendChild(this._debugCanvas);
  54884. this._registerFunc = function () {
  54885. _this.drawDebugCanvas();
  54886. };
  54887. this._scene.registerBeforeRender(this._registerFunc);
  54888. }
  54889. if (this._registerFunc) {
  54890. var workingArray = this.getByteFrequencyData();
  54891. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  54892. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  54893. // Draw the frequency domain chart.
  54894. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  54895. var value = workingArray[i];
  54896. var percent = value / this.BARGRAPHAMPLITUDE;
  54897. var height = this.DEBUGCANVASSIZE.height * percent;
  54898. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  54899. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  54900. var hue = i / this.getFrequencyBinCount() * 360;
  54901. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  54902. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  54903. }
  54904. }
  54905. }
  54906. };
  54907. Analyser.prototype.stopDebugCanvas = function () {
  54908. if (this._debugCanvas) {
  54909. this._scene.unregisterBeforeRender(this._registerFunc);
  54910. this._registerFunc = null;
  54911. document.body.removeChild(this._debugCanvas);
  54912. this._debugCanvas = null;
  54913. this._debugCanvasContext = null;
  54914. }
  54915. };
  54916. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  54917. if (this._audioEngine.canUseWebAudio) {
  54918. inputAudioNode.connect(this._webAudioAnalyser);
  54919. this._webAudioAnalyser.connect(outputAudioNode);
  54920. }
  54921. };
  54922. Analyser.prototype.dispose = function () {
  54923. if (this._audioEngine.canUseWebAudio) {
  54924. this._webAudioAnalyser.disconnect();
  54925. }
  54926. };
  54927. return Analyser;
  54928. }());
  54929. BABYLON.Analyser = Analyser;
  54930. })(BABYLON || (BABYLON = {}));
  54931. var BABYLON;
  54932. (function (BABYLON) {
  54933. var DepthRenderer = (function () {
  54934. function DepthRenderer(scene, type) {
  54935. var _this = this;
  54936. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  54937. this._viewMatrix = BABYLON.Matrix.Zero();
  54938. this._projectionMatrix = BABYLON.Matrix.Zero();
  54939. this._transformMatrix = BABYLON.Matrix.Zero();
  54940. this._worldViewProjection = BABYLON.Matrix.Zero();
  54941. this._scene = scene;
  54942. var engine = scene.getEngine();
  54943. // Render target
  54944. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  54945. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54946. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54947. this._depthMap.refreshRate = 1;
  54948. this._depthMap.renderParticles = false;
  54949. this._depthMap.renderList = null;
  54950. // set default depth value to 1.0 (far away)
  54951. this._depthMap.onClearObservable.add(function (engine) {
  54952. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  54953. });
  54954. // Custom render function
  54955. var renderSubMesh = function (subMesh) {
  54956. var mesh = subMesh.getRenderingMesh();
  54957. var scene = _this._scene;
  54958. var engine = scene.getEngine();
  54959. // Culling
  54960. engine.setState(subMesh.getMaterial().backFaceCulling);
  54961. // Managing instances
  54962. var batch = mesh._getInstancesRenderList(subMesh._id);
  54963. if (batch.mustReturn) {
  54964. return;
  54965. }
  54966. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  54967. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54968. engine.enableEffect(_this._effect);
  54969. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  54970. var material = subMesh.getMaterial();
  54971. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  54972. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  54973. // Alpha test
  54974. if (material && material.needAlphaTesting()) {
  54975. var alphaTexture = material.getAlphaTestTexture();
  54976. _this._effect.setTexture("diffuseSampler", alphaTexture);
  54977. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54978. }
  54979. // Bones
  54980. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54981. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54982. }
  54983. // Draw
  54984. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  54985. }
  54986. };
  54987. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  54988. var index;
  54989. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54990. renderSubMesh(opaqueSubMeshes.data[index]);
  54991. }
  54992. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54993. renderSubMesh(alphaTestSubMeshes.data[index]);
  54994. }
  54995. };
  54996. }
  54997. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  54998. var material = subMesh.getMaterial();
  54999. if (material.disableDepthWrite) {
  55000. return false;
  55001. }
  55002. var defines = [];
  55003. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55004. var mesh = subMesh.getMesh();
  55005. var scene = mesh.getScene();
  55006. // Alpha test
  55007. if (material && material.needAlphaTesting()) {
  55008. defines.push("#define ALPHATEST");
  55009. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55010. attribs.push(BABYLON.VertexBuffer.UVKind);
  55011. defines.push("#define UV1");
  55012. }
  55013. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55014. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55015. defines.push("#define UV2");
  55016. }
  55017. }
  55018. // Bones
  55019. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55020. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55021. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55022. if (mesh.numBoneInfluencers > 4) {
  55023. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55024. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55025. }
  55026. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55027. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55028. }
  55029. else {
  55030. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55031. }
  55032. // Instances
  55033. if (useInstances) {
  55034. defines.push("#define INSTANCES");
  55035. attribs.push("world0");
  55036. attribs.push("world1");
  55037. attribs.push("world2");
  55038. attribs.push("world3");
  55039. }
  55040. // Get correct effect
  55041. var join = defines.join("\n");
  55042. if (this._cachedDefines !== join) {
  55043. this._cachedDefines = join;
  55044. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  55045. }
  55046. return this._effect.isReady();
  55047. };
  55048. DepthRenderer.prototype.getDepthMap = function () {
  55049. return this._depthMap;
  55050. };
  55051. // Methods
  55052. DepthRenderer.prototype.dispose = function () {
  55053. this._depthMap.dispose();
  55054. };
  55055. return DepthRenderer;
  55056. }());
  55057. BABYLON.DepthRenderer = DepthRenderer;
  55058. })(BABYLON || (BABYLON = {}));
  55059. var BABYLON;
  55060. (function (BABYLON) {
  55061. var SSAORenderingPipeline = (function (_super) {
  55062. __extends(SSAORenderingPipeline, _super);
  55063. /**
  55064. * @constructor
  55065. * @param {string} name - The rendering pipeline name
  55066. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55067. * @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 }
  55068. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55069. */
  55070. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  55071. var _this = this;
  55072. _super.call(this, scene.getEngine(), name);
  55073. // Members
  55074. /**
  55075. * The PassPostProcess id in the pipeline that contains the original scene color
  55076. * @type {string}
  55077. */
  55078. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  55079. /**
  55080. * The SSAO PostProcess id in the pipeline
  55081. * @type {string}
  55082. */
  55083. this.SSAORenderEffect = "SSAORenderEffect";
  55084. /**
  55085. * The horizontal blur PostProcess id in the pipeline
  55086. * @type {string}
  55087. */
  55088. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  55089. /**
  55090. * The vertical blur PostProcess id in the pipeline
  55091. * @type {string}
  55092. */
  55093. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  55094. /**
  55095. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  55096. * @type {string}
  55097. */
  55098. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  55099. /**
  55100. * The output strength of the SSAO post-process. Default value is 1.0.
  55101. * @type {number}
  55102. */
  55103. this.totalStrength = 1.0;
  55104. /**
  55105. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  55106. * @type {number}
  55107. */
  55108. this.radius = 0.0001;
  55109. /**
  55110. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  55111. * Must not be equal to fallOff and superior to fallOff.
  55112. * Default value is 0.975
  55113. * @type {number}
  55114. */
  55115. this.area = 0.0075;
  55116. /**
  55117. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  55118. * Must not be equal to area and inferior to area.
  55119. * Default value is 0.0
  55120. * @type {number}
  55121. */
  55122. this.fallOff = 0.000001;
  55123. /**
  55124. * The base color of the SSAO post-process
  55125. * The final result is "base + ssao" between [0, 1]
  55126. * @type {number}
  55127. */
  55128. this.base = 0.5;
  55129. this._firstUpdate = true;
  55130. this._scene = scene;
  55131. // Set up assets
  55132. this._createRandomTexture();
  55133. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55134. var ssaoRatio = ratio.ssaoRatio || ratio;
  55135. var combineRatio = ratio.combineRatio || ratio;
  55136. this._ratio = {
  55137. ssaoRatio: ssaoRatio,
  55138. combineRatio: combineRatio
  55139. };
  55140. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  55141. this._createSSAOPostProcess(ssaoRatio);
  55142. this._createBlurPostProcess(ssaoRatio);
  55143. this._createSSAOCombinePostProcess(combineRatio);
  55144. // Set up pipeline
  55145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  55146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  55147. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  55148. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  55149. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  55150. // Finish
  55151. scene.postProcessRenderPipelineManager.addPipeline(this);
  55152. if (cameras)
  55153. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55154. }
  55155. // Public Methods
  55156. /**
  55157. * Returns the horizontal blur PostProcess
  55158. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  55159. */
  55160. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  55161. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  55162. return null;
  55163. };
  55164. /**
  55165. * Returns the vertical blur PostProcess
  55166. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  55167. */
  55168. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  55169. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  55170. return null;
  55171. };
  55172. /**
  55173. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  55174. */
  55175. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55176. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55177. for (var i = 0; i < this._scene.cameras.length; i++) {
  55178. var camera = this._scene.cameras[i];
  55179. this._originalColorPostProcess.dispose(camera);
  55180. this._ssaoPostProcess.dispose(camera);
  55181. this._blurHPostProcess.dispose(camera);
  55182. this._blurVPostProcess.dispose(camera);
  55183. this._ssaoCombinePostProcess.dispose(camera);
  55184. }
  55185. this._randomTexture.dispose();
  55186. if (disableDepthRender)
  55187. this._scene.disableDepthRenderer();
  55188. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55189. };
  55190. // Private Methods
  55191. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  55192. var _this = this;
  55193. /*
  55194. var samplerOffsets = [
  55195. -8.0, -6.0, -4.0, -2.0,
  55196. 0.0,
  55197. 2.0, 4.0, 6.0, 8.0
  55198. ];
  55199. */
  55200. var samples = 16;
  55201. var samplerOffsets = [];
  55202. for (var i = -8; i < 8; i++) {
  55203. samplerOffsets.push(i * 2);
  55204. }
  55205. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  55206. this._blurHPostProcess.onApply = function (effect) {
  55207. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  55208. effect.setTexture("depthSampler", _this._depthTexture);
  55209. if (_this._firstUpdate) {
  55210. effect.setArray("samplerOffsets", samplerOffsets);
  55211. }
  55212. };
  55213. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  55214. this._blurVPostProcess.onApply = function (effect) {
  55215. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  55216. effect.setTexture("depthSampler", _this._depthTexture);
  55217. if (_this._firstUpdate) {
  55218. effect.setArray("samplerOffsets", samplerOffsets);
  55219. _this._firstUpdate = false;
  55220. }
  55221. };
  55222. };
  55223. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  55224. var _this = this;
  55225. var numSamples = 16;
  55226. var sampleSphere = [
  55227. 0.5381, 0.1856, -0.4319,
  55228. 0.1379, 0.2486, 0.4430,
  55229. 0.3371, 0.5679, -0.0057,
  55230. -0.6999, -0.0451, -0.0019,
  55231. 0.0689, -0.1598, -0.8547,
  55232. 0.0560, 0.0069, -0.1843,
  55233. -0.0146, 0.1402, 0.0762,
  55234. 0.0100, -0.1924, -0.0344,
  55235. -0.3577, -0.5301, -0.4358,
  55236. -0.3169, 0.1063, 0.0158,
  55237. 0.0103, -0.5869, 0.0046,
  55238. -0.0897, -0.4940, 0.3287,
  55239. 0.7119, -0.0154, -0.0918,
  55240. -0.0533, 0.0596, -0.5411,
  55241. 0.0352, -0.0631, 0.5460,
  55242. -0.4776, 0.2847, -0.0271
  55243. ];
  55244. var samplesFactor = 1.0 / numSamples;
  55245. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  55246. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  55247. "area", "fallOff", "base", "range", "viewport"
  55248. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  55249. var viewport = new BABYLON.Vector2(0, 0);
  55250. this._ssaoPostProcess.onApply = function (effect) {
  55251. if (_this._firstUpdate) {
  55252. effect.setArray3("sampleSphere", sampleSphere);
  55253. effect.setFloat("samplesFactor", samplesFactor);
  55254. effect.setFloat("randTextureTiles", 4.0);
  55255. }
  55256. effect.setFloat("totalStrength", _this.totalStrength);
  55257. effect.setFloat("radius", _this.radius);
  55258. effect.setFloat("area", _this.area);
  55259. effect.setFloat("fallOff", _this.fallOff);
  55260. effect.setFloat("base", _this.base);
  55261. effect.setTexture("textureSampler", _this._depthTexture);
  55262. effect.setTexture("randomSampler", _this._randomTexture);
  55263. };
  55264. };
  55265. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  55266. var _this = this;
  55267. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55268. this._ssaoCombinePostProcess.onApply = function (effect) {
  55269. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  55270. };
  55271. };
  55272. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  55273. var size = 512;
  55274. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55275. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55276. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55277. var context = this._randomTexture.getContext();
  55278. var rand = function (min, max) {
  55279. return Math.random() * (max - min) + min;
  55280. };
  55281. var randVector = BABYLON.Vector3.Zero();
  55282. for (var x = 0; x < size; x++) {
  55283. for (var y = 0; y < size; y++) {
  55284. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  55285. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  55286. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  55287. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  55288. context.fillRect(x, y, 1, 1);
  55289. }
  55290. }
  55291. this._randomTexture.update(false);
  55292. };
  55293. __decorate([
  55294. BABYLON.serialize()
  55295. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  55296. __decorate([
  55297. BABYLON.serialize()
  55298. ], SSAORenderingPipeline.prototype, "radius", void 0);
  55299. __decorate([
  55300. BABYLON.serialize()
  55301. ], SSAORenderingPipeline.prototype, "area", void 0);
  55302. __decorate([
  55303. BABYLON.serialize()
  55304. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  55305. __decorate([
  55306. BABYLON.serialize()
  55307. ], SSAORenderingPipeline.prototype, "base", void 0);
  55308. __decorate([
  55309. BABYLON.serialize()
  55310. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  55311. return SSAORenderingPipeline;
  55312. }(BABYLON.PostProcessRenderPipeline));
  55313. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  55314. })(BABYLON || (BABYLON = {}));
  55315. var BABYLON;
  55316. (function (BABYLON) {
  55317. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  55318. var VolumetricLightScatteringPostProcess = (function (_super) {
  55319. __extends(VolumetricLightScatteringPostProcess, _super);
  55320. /**
  55321. * @constructor
  55322. * @param {string} name - The post-process name
  55323. * @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)
  55324. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  55325. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  55326. * @param {number} samples - The post-process quality, default 100
  55327. * @param {number} samplingMode - The post-process filtering mode
  55328. * @param {BABYLON.Engine} engine - The babylon engine
  55329. * @param {boolean} reusable - If the post-process is reusable
  55330. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  55331. */
  55332. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  55333. var _this = this;
  55334. if (samples === void 0) { samples = 100; }
  55335. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55336. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  55337. this._screenCoordinates = BABYLON.Vector2.Zero();
  55338. /**
  55339. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  55340. * @type {Vector3}
  55341. */
  55342. this.customMeshPosition = BABYLON.Vector3.Zero();
  55343. /**
  55344. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  55345. * @type {boolean}
  55346. */
  55347. this.useCustomMeshPosition = false;
  55348. /**
  55349. * If the post-process should inverse the light scattering direction
  55350. * @type {boolean}
  55351. */
  55352. this.invert = true;
  55353. /**
  55354. * Array containing the excluded meshes not rendered in the internal pass
  55355. */
  55356. this.excludedMeshes = new Array();
  55357. /**
  55358. * Controls the overall intensity of the post-process
  55359. * @type {number}
  55360. */
  55361. this.exposure = 0.3;
  55362. /**
  55363. * Dissipates each sample's contribution in range [0, 1]
  55364. * @type {number}
  55365. */
  55366. this.decay = 0.96815;
  55367. /**
  55368. * Controls the overall intensity of each sample
  55369. * @type {number}
  55370. */
  55371. this.weight = 0.58767;
  55372. /**
  55373. * Controls the density of each sample
  55374. * @type {number}
  55375. */
  55376. this.density = 0.926;
  55377. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  55378. var engine = scene.getEngine();
  55379. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  55380. // Configure mesh
  55381. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  55382. // Configure
  55383. this._createPass(scene, ratio.passRatio || ratio);
  55384. this.onActivate = function (camera) {
  55385. if (!_this.isSupported) {
  55386. _this.dispose(camera);
  55387. }
  55388. _this.onActivate = null;
  55389. };
  55390. this.onApplyObservable.add(function (effect) {
  55391. _this._updateMeshScreenCoordinates(scene);
  55392. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  55393. effect.setFloat("exposure", _this.exposure);
  55394. effect.setFloat("decay", _this.decay);
  55395. effect.setFloat("weight", _this.weight);
  55396. effect.setFloat("density", _this.density);
  55397. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  55398. });
  55399. }
  55400. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  55401. get: function () {
  55402. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55403. return false;
  55404. },
  55405. set: function (useDiffuseColor) {
  55406. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  55407. },
  55408. enumerable: true,
  55409. configurable: true
  55410. });
  55411. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  55412. var mesh = subMesh.getMesh();
  55413. // Render this.mesh as default
  55414. if (mesh === this.mesh) {
  55415. return mesh.material.isReady(mesh);
  55416. }
  55417. var defines = [];
  55418. var attribs = [BABYLON.VertexBuffer.PositionKind];
  55419. var material = subMesh.getMaterial();
  55420. var needUV = false;
  55421. // Alpha test
  55422. if (material) {
  55423. if (material.needAlphaTesting()) {
  55424. defines.push("#define ALPHATEST");
  55425. }
  55426. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  55427. attribs.push(BABYLON.VertexBuffer.UVKind);
  55428. defines.push("#define UV1");
  55429. }
  55430. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  55431. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  55432. defines.push("#define UV2");
  55433. }
  55434. }
  55435. // Bones
  55436. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55437. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55438. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55439. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55440. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55441. }
  55442. else {
  55443. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55444. }
  55445. // Instances
  55446. if (useInstances) {
  55447. defines.push("#define INSTANCES");
  55448. attribs.push("world0");
  55449. attribs.push("world1");
  55450. attribs.push("world2");
  55451. attribs.push("world3");
  55452. }
  55453. // Get correct effect
  55454. var join = defines.join("\n");
  55455. if (this._cachedDefines !== join) {
  55456. this._cachedDefines = join;
  55457. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  55458. }
  55459. return this._volumetricLightScatteringPass.isReady();
  55460. };
  55461. /**
  55462. * Sets the new light position for light scattering effect
  55463. * @param {BABYLON.Vector3} The new custom light position
  55464. */
  55465. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  55466. this.customMeshPosition = position;
  55467. };
  55468. /**
  55469. * Returns the light position for light scattering effect
  55470. * @return {BABYLON.Vector3} The custom light position
  55471. */
  55472. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  55473. return this.customMeshPosition;
  55474. };
  55475. /**
  55476. * Disposes the internal assets and detaches the post-process from the camera
  55477. */
  55478. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  55479. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  55480. if (rttIndex !== -1) {
  55481. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  55482. }
  55483. this._volumetricLightScatteringRTT.dispose();
  55484. _super.prototype.dispose.call(this, camera);
  55485. };
  55486. /**
  55487. * Returns the render target texture used by the post-process
  55488. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  55489. */
  55490. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  55491. return this._volumetricLightScatteringRTT;
  55492. };
  55493. // Private methods
  55494. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  55495. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  55496. return true;
  55497. }
  55498. return false;
  55499. };
  55500. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  55501. var _this = this;
  55502. var engine = scene.getEngine();
  55503. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55504. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55505. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55506. this._volumetricLightScatteringRTT.renderList = null;
  55507. this._volumetricLightScatteringRTT.renderParticles = false;
  55508. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  55509. // Custom render function for submeshes
  55510. var renderSubMesh = function (subMesh) {
  55511. var mesh = subMesh.getRenderingMesh();
  55512. if (_this._meshExcluded(mesh)) {
  55513. return;
  55514. }
  55515. var scene = mesh.getScene();
  55516. var engine = scene.getEngine();
  55517. // Culling
  55518. engine.setState(subMesh.getMaterial().backFaceCulling);
  55519. // Managing instances
  55520. var batch = mesh._getInstancesRenderList(subMesh._id);
  55521. if (batch.mustReturn) {
  55522. return;
  55523. }
  55524. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  55525. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  55526. var effect = _this._volumetricLightScatteringPass;
  55527. if (mesh === _this.mesh) {
  55528. effect = subMesh.getMaterial().getEffect();
  55529. }
  55530. engine.enableEffect(effect);
  55531. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  55532. if (mesh === _this.mesh) {
  55533. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  55534. }
  55535. else {
  55536. var material = subMesh.getMaterial();
  55537. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  55538. // Alpha test
  55539. if (material && material.needAlphaTesting()) {
  55540. var alphaTexture = material.getAlphaTestTexture();
  55541. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  55542. if (alphaTexture) {
  55543. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  55544. }
  55545. }
  55546. // Bones
  55547. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  55548. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  55549. }
  55550. }
  55551. // Draw
  55552. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  55553. }
  55554. };
  55555. // Render target texture callbacks
  55556. var savedSceneClearColor;
  55557. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  55558. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  55559. savedSceneClearColor = scene.clearColor;
  55560. scene.clearColor = sceneClearColor;
  55561. });
  55562. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  55563. scene.clearColor = savedSceneClearColor;
  55564. });
  55565. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  55566. var engine = scene.getEngine();
  55567. var index;
  55568. for (index = 0; index < opaqueSubMeshes.length; index++) {
  55569. renderSubMesh(opaqueSubMeshes.data[index]);
  55570. }
  55571. engine.setAlphaTesting(true);
  55572. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  55573. renderSubMesh(alphaTestSubMeshes.data[index]);
  55574. }
  55575. engine.setAlphaTesting(false);
  55576. if (transparentSubMeshes.length) {
  55577. // Sort sub meshes
  55578. for (index = 0; index < transparentSubMeshes.length; index++) {
  55579. var submesh = transparentSubMeshes.data[index];
  55580. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  55581. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  55582. }
  55583. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  55584. sortedArray.sort(function (a, b) {
  55585. // Alpha index first
  55586. if (a._alphaIndex > b._alphaIndex) {
  55587. return 1;
  55588. }
  55589. if (a._alphaIndex < b._alphaIndex) {
  55590. return -1;
  55591. }
  55592. // Then distance to camera
  55593. if (a._distanceToCamera < b._distanceToCamera) {
  55594. return 1;
  55595. }
  55596. if (a._distanceToCamera > b._distanceToCamera) {
  55597. return -1;
  55598. }
  55599. return 0;
  55600. });
  55601. // Render sub meshes
  55602. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55603. for (index = 0; index < sortedArray.length; index++) {
  55604. renderSubMesh(sortedArray[index]);
  55605. }
  55606. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55607. }
  55608. };
  55609. };
  55610. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  55611. var transform = scene.getTransformMatrix();
  55612. var meshPosition;
  55613. if (this.useCustomMeshPosition) {
  55614. meshPosition = this.customMeshPosition;
  55615. }
  55616. else if (this.attachedNode) {
  55617. meshPosition = this.attachedNode.position;
  55618. }
  55619. else {
  55620. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  55621. }
  55622. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  55623. this._screenCoordinates.x = pos.x / this._viewPort.width;
  55624. this._screenCoordinates.y = pos.y / this._viewPort.height;
  55625. if (this.invert)
  55626. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  55627. };
  55628. // Static methods
  55629. /**
  55630. * Creates a default mesh for the Volumeric Light Scattering post-process
  55631. * @param {string} The mesh name
  55632. * @param {BABYLON.Scene} The scene where to create the mesh
  55633. * @return {BABYLON.Mesh} the default mesh
  55634. */
  55635. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  55636. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  55637. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55638. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  55639. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  55640. mesh.material = material;
  55641. return mesh;
  55642. };
  55643. __decorate([
  55644. BABYLON.serializeAsVector3()
  55645. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  55646. __decorate([
  55647. BABYLON.serialize()
  55648. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  55649. __decorate([
  55650. BABYLON.serialize()
  55651. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  55652. __decorate([
  55653. BABYLON.serializeAsMeshReference()
  55654. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  55655. __decorate([
  55656. BABYLON.serialize()
  55657. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  55658. __decorate([
  55659. BABYLON.serialize()
  55660. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  55661. __decorate([
  55662. BABYLON.serialize()
  55663. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  55664. __decorate([
  55665. BABYLON.serialize()
  55666. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  55667. __decorate([
  55668. BABYLON.serialize()
  55669. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  55670. return VolumetricLightScatteringPostProcess;
  55671. }(BABYLON.PostProcess));
  55672. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  55673. })(BABYLON || (BABYLON = {}));
  55674. // BABYLON.JS Chromatic Aberration GLSL Shader
  55675. // Author: Olivier Guyot
  55676. // Separates very slightly R, G and B colors on the edges of the screen
  55677. // Inspired by Francois Tarlier & Martins Upitis
  55678. var BABYLON;
  55679. (function (BABYLON) {
  55680. var LensRenderingPipeline = (function (_super) {
  55681. __extends(LensRenderingPipeline, _super);
  55682. /**
  55683. * @constructor
  55684. *
  55685. * Effect parameters are as follow:
  55686. * {
  55687. * chromatic_aberration: number; // from 0 to x (1 for realism)
  55688. * edge_blur: number; // from 0 to x (1 for realism)
  55689. * distortion: number; // from 0 to x (1 for realism)
  55690. * grain_amount: number; // from 0 to 1
  55691. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  55692. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  55693. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  55694. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  55695. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  55696. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  55697. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  55698. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  55699. * }
  55700. * Note: if an effect parameter is unset, effect is disabled
  55701. *
  55702. * @param {string} name - The rendering pipeline name
  55703. * @param {object} parameters - An object containing all parameters (see above)
  55704. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55705. * @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)
  55706. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55707. */
  55708. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  55709. var _this = this;
  55710. if (ratio === void 0) { ratio = 1.0; }
  55711. _super.call(this, scene.getEngine(), name);
  55712. // Lens effects can be of the following:
  55713. // - chromatic aberration (slight shift of RGB colors)
  55714. // - blur on the edge of the lens
  55715. // - lens distortion
  55716. // - depth-of-field blur & highlights enhancing
  55717. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  55718. // - grain effect (noise or custom texture)
  55719. // Two additional texture samplers are needed:
  55720. // - depth map (for depth-of-field)
  55721. // - grain texture
  55722. /**
  55723. * The chromatic aberration PostProcess id in the pipeline
  55724. * @type {string}
  55725. */
  55726. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  55727. /**
  55728. * The highlights enhancing PostProcess id in the pipeline
  55729. * @type {string}
  55730. */
  55731. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  55732. /**
  55733. * The depth-of-field PostProcess id in the pipeline
  55734. * @type {string}
  55735. */
  55736. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  55737. this._scene = scene;
  55738. // Fetch texture samplers
  55739. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  55740. if (parameters.grain_texture) {
  55741. this._grainTexture = parameters.grain_texture;
  55742. }
  55743. else {
  55744. this._createGrainTexture();
  55745. }
  55746. // save parameters
  55747. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  55748. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  55749. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  55750. this._distortion = parameters.distortion ? parameters.distortion : 0;
  55751. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  55752. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  55753. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  55754. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  55755. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  55756. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  55757. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  55758. // Create effects
  55759. this._createChromaticAberrationPostProcess(ratio);
  55760. this._createHighlightsPostProcess(ratio);
  55761. this._createDepthOfFieldPostProcess(ratio / 4);
  55762. // Set up pipeline
  55763. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  55764. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  55765. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  55766. if (this._highlightsGain === -1) {
  55767. this._disableEffect(this.HighlightsEnhancingEffect, null);
  55768. }
  55769. // Finish
  55770. scene.postProcessRenderPipelineManager.addPipeline(this);
  55771. if (cameras) {
  55772. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55773. }
  55774. }
  55775. // public methods (self explanatory)
  55776. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  55777. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  55778. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  55779. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  55780. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  55781. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  55782. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  55783. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  55784. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  55785. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  55786. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  55787. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  55788. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  55789. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  55790. };
  55791. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  55792. this._highlightsPostProcess.updateEffect();
  55793. };
  55794. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  55795. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  55796. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  55797. this._highlightsGain = amount;
  55798. };
  55799. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  55800. if (this._highlightsGain === -1) {
  55801. this._highlightsGain = 1.0;
  55802. }
  55803. this._highlightsThreshold = amount;
  55804. };
  55805. LensRenderingPipeline.prototype.disableHighlights = function () {
  55806. this._highlightsGain = -1;
  55807. };
  55808. /**
  55809. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  55810. */
  55811. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  55812. if (disableDepthRender === void 0) { disableDepthRender = false; }
  55813. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55814. this._chromaticAberrationPostProcess = undefined;
  55815. this._highlightsPostProcess = undefined;
  55816. this._depthOfFieldPostProcess = undefined;
  55817. this._grainTexture.dispose();
  55818. if (disableDepthRender)
  55819. this._scene.disableDepthRenderer();
  55820. };
  55821. // colors shifting and distortion
  55822. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  55823. var _this = this;
  55824. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  55825. [], // samplers
  55826. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55827. this._chromaticAberrationPostProcess.onApply = function (effect) {
  55828. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  55829. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55830. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55831. };
  55832. };
  55833. // highlights enhancing
  55834. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  55835. var _this = this;
  55836. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  55837. [], // samplers
  55838. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  55839. this._highlightsPostProcess.onApply = function (effect) {
  55840. effect.setFloat('gain', _this._highlightsGain);
  55841. effect.setFloat('threshold', _this._highlightsThreshold);
  55842. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  55843. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55844. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55845. };
  55846. };
  55847. // colors shifting and distortion
  55848. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  55849. var _this = this;
  55850. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  55851. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  55852. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  55853. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  55854. this._depthOfFieldPostProcess.onApply = function (effect) {
  55855. effect.setTexture("depthSampler", _this._depthTexture);
  55856. effect.setTexture("grainSampler", _this._grainTexture);
  55857. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  55858. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  55859. effect.setFloat('grain_amount', _this._grainAmount);
  55860. effect.setBool('blur_noise', _this._blurNoise);
  55861. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  55862. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  55863. effect.setFloat('distortion', _this._distortion);
  55864. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  55865. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  55866. effect.setFloat('aperture', _this._dofAperture);
  55867. effect.setFloat('darken', _this._dofDarken);
  55868. effect.setFloat('edge_blur', _this._edgeBlur);
  55869. effect.setBool('highlights', (_this._highlightsGain !== -1));
  55870. effect.setFloat('near', _this._scene.activeCamera.minZ);
  55871. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  55872. };
  55873. };
  55874. // creates a black and white random noise texture, 512x512
  55875. LensRenderingPipeline.prototype._createGrainTexture = function () {
  55876. var size = 512;
  55877. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  55878. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  55879. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  55880. var context = this._grainTexture.getContext();
  55881. var rand = function (min, max) {
  55882. return Math.random() * (max - min) + min;
  55883. };
  55884. var value;
  55885. for (var x = 0; x < size; x++) {
  55886. for (var y = 0; y < size; y++) {
  55887. value = Math.floor(rand(0.42, 0.58) * 255);
  55888. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  55889. context.fillRect(x, y, 1, 1);
  55890. }
  55891. }
  55892. this._grainTexture.update(false);
  55893. };
  55894. return LensRenderingPipeline;
  55895. }(BABYLON.PostProcessRenderPipeline));
  55896. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  55897. })(BABYLON || (BABYLON = {}));
  55898. //
  55899. // This post-process allows the modification of rendered colors by using
  55900. // a 'look-up table' (LUT). This effect is also called Color Grading.
  55901. //
  55902. // The object needs to be provided an url to a texture containing the color
  55903. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  55904. // Use an image editing software to tweak the LUT to match your needs.
  55905. //
  55906. // For an example of a color LUT, see here:
  55907. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  55908. // For explanations on color grading, see here:
  55909. // http://udn.epicgames.com/Three/ColorGrading.html
  55910. //
  55911. var BABYLON;
  55912. (function (BABYLON) {
  55913. var ColorCorrectionPostProcess = (function (_super) {
  55914. __extends(ColorCorrectionPostProcess, _super);
  55915. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  55916. var _this = this;
  55917. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  55918. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  55919. this._colorTableTexture.anisotropicFilteringLevel = 1;
  55920. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55921. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  55922. this.onApply = function (effect) {
  55923. effect.setTexture("colorTable", _this._colorTableTexture);
  55924. };
  55925. }
  55926. return ColorCorrectionPostProcess;
  55927. }(BABYLON.PostProcess));
  55928. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  55929. })(BABYLON || (BABYLON = {}));
  55930. var BABYLON;
  55931. (function (BABYLON) {
  55932. var AnaglyphFreeCamera = (function (_super) {
  55933. __extends(AnaglyphFreeCamera, _super);
  55934. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  55935. _super.call(this, name, position, scene);
  55936. this.interaxialDistance = interaxialDistance;
  55937. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55938. }
  55939. AnaglyphFreeCamera.prototype.getTypeName = function () {
  55940. return "AnaglyphFreeCamera";
  55941. };
  55942. return AnaglyphFreeCamera;
  55943. }(BABYLON.FreeCamera));
  55944. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  55945. var AnaglyphArcRotateCamera = (function (_super) {
  55946. __extends(AnaglyphArcRotateCamera, _super);
  55947. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  55948. _super.call(this, name, alpha, beta, radius, target, scene);
  55949. this.interaxialDistance = interaxialDistance;
  55950. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55951. }
  55952. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  55953. return "AnaglyphArcRotateCamera";
  55954. };
  55955. return AnaglyphArcRotateCamera;
  55956. }(BABYLON.ArcRotateCamera));
  55957. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  55958. var AnaglyphGamepadCamera = (function (_super) {
  55959. __extends(AnaglyphGamepadCamera, _super);
  55960. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  55961. _super.call(this, name, position, scene);
  55962. this.interaxialDistance = interaxialDistance;
  55963. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55964. }
  55965. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  55966. return "AnaglyphGamepadCamera";
  55967. };
  55968. return AnaglyphGamepadCamera;
  55969. }(BABYLON.GamepadCamera));
  55970. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  55971. var AnaglyphUniversalCamera = (function (_super) {
  55972. __extends(AnaglyphUniversalCamera, _super);
  55973. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  55974. _super.call(this, name, position, scene);
  55975. this.interaxialDistance = interaxialDistance;
  55976. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  55977. }
  55978. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  55979. return "AnaglyphUniversalCamera";
  55980. };
  55981. return AnaglyphUniversalCamera;
  55982. }(BABYLON.UniversalCamera));
  55983. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  55984. var StereoscopicFreeCamera = (function (_super) {
  55985. __extends(StereoscopicFreeCamera, _super);
  55986. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  55987. _super.call(this, name, position, scene);
  55988. this.interaxialDistance = interaxialDistance;
  55989. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  55990. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  55991. }
  55992. StereoscopicFreeCamera.prototype.getTypeName = function () {
  55993. return "StereoscopicFreeCamera";
  55994. };
  55995. return StereoscopicFreeCamera;
  55996. }(BABYLON.FreeCamera));
  55997. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  55998. var StereoscopicArcRotateCamera = (function (_super) {
  55999. __extends(StereoscopicArcRotateCamera, _super);
  56000. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  56001. _super.call(this, name, alpha, beta, radius, target, scene);
  56002. this.interaxialDistance = interaxialDistance;
  56003. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56004. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56005. }
  56006. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  56007. return "StereoscopicArcRotateCamera";
  56008. };
  56009. return StereoscopicArcRotateCamera;
  56010. }(BABYLON.ArcRotateCamera));
  56011. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  56012. var StereoscopicGamepadCamera = (function (_super) {
  56013. __extends(StereoscopicGamepadCamera, _super);
  56014. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56015. _super.call(this, name, position, scene);
  56016. this.interaxialDistance = interaxialDistance;
  56017. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56018. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56019. }
  56020. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  56021. return "StereoscopicGamepadCamera";
  56022. };
  56023. return StereoscopicGamepadCamera;
  56024. }(BABYLON.GamepadCamera));
  56025. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  56026. var StereoscopicUniversalCamera = (function (_super) {
  56027. __extends(StereoscopicUniversalCamera, _super);
  56028. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  56029. _super.call(this, name, position, scene);
  56030. this.interaxialDistance = interaxialDistance;
  56031. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  56032. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  56033. }
  56034. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  56035. return "StereoscopicUniversalCamera";
  56036. };
  56037. return StereoscopicUniversalCamera;
  56038. }(BABYLON.UniversalCamera));
  56039. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  56040. })(BABYLON || (BABYLON = {}));
  56041. var BABYLON;
  56042. (function (BABYLON) {
  56043. var HDRRenderingPipeline = (function (_super) {
  56044. __extends(HDRRenderingPipeline, _super);
  56045. /**
  56046. * @constructor
  56047. * @param {string} name - The rendering pipeline name
  56048. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  56049. * @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)
  56050. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  56051. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  56052. */
  56053. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  56054. var _this = this;
  56055. if (originalPostProcess === void 0) { originalPostProcess = null; }
  56056. _super.call(this, scene.getEngine(), name);
  56057. /**
  56058. * Public members
  56059. */
  56060. // Gaussian Blur
  56061. /**
  56062. * Gaussian blur coefficient
  56063. * @type {number}
  56064. */
  56065. this.gaussCoeff = 0.3;
  56066. /**
  56067. * Gaussian blur mean
  56068. * @type {number}
  56069. */
  56070. this.gaussMean = 1.0;
  56071. /**
  56072. * Gaussian blur standard deviation
  56073. * @type {number}
  56074. */
  56075. this.gaussStandDev = 0.8;
  56076. /**
  56077. * Gaussian blur multiplier. Multiplies the blur effect
  56078. * @type {number}
  56079. */
  56080. this.gaussMultiplier = 4.0;
  56081. // HDR
  56082. /**
  56083. * Exposure, controls the overall intensity of the pipeline
  56084. * @type {number}
  56085. */
  56086. this.exposure = 1.0;
  56087. /**
  56088. * Minimum luminance that the post-process can output. Luminance is >= 0
  56089. * @type {number}
  56090. */
  56091. this.minimumLuminance = 1.0;
  56092. /**
  56093. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  56094. * @type {number}
  56095. */
  56096. this.maximumLuminance = 1e20;
  56097. /**
  56098. * Increase rate for luminance: eye adaptation speed to dark
  56099. * @type {number}
  56100. */
  56101. this.luminanceIncreaserate = 0.5;
  56102. /**
  56103. * Decrease rate for luminance: eye adaptation speed to bright
  56104. * @type {number}
  56105. */
  56106. this.luminanceDecreaseRate = 0.5;
  56107. // Bright pass
  56108. /**
  56109. * Minimum luminance needed to compute HDR
  56110. * @type {number}
  56111. */
  56112. this.brightThreshold = 0.8;
  56113. this._needUpdate = true;
  56114. this._scene = scene;
  56115. // Bright pass
  56116. this._createBrightPassPostProcess(scene, ratio);
  56117. // Down sample X4
  56118. this._createDownSampleX4PostProcess(scene, ratio);
  56119. // Create gaussian blur post-processes
  56120. this._createGaussianBlurPostProcess(scene, ratio);
  56121. // Texture adder
  56122. this._createTextureAdderPostProcess(scene, ratio);
  56123. // Luminance generator
  56124. this._createLuminanceGeneratorPostProcess(scene);
  56125. // HDR
  56126. this._createHDRPostProcess(scene, ratio);
  56127. // Pass postprocess
  56128. if (originalPostProcess === null) {
  56129. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  56130. }
  56131. else {
  56132. this._originalPostProcess = originalPostProcess;
  56133. }
  56134. // Configure pipeline
  56135. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  56136. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  56137. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  56138. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  56139. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  56140. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  56141. var addDownSamplerPostProcess = function (id) {
  56142. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  56143. };
  56144. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  56145. addDownSamplerPostProcess(i);
  56146. }
  56147. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  56148. // Finish
  56149. scene.postProcessRenderPipelineManager.addPipeline(this);
  56150. if (cameras !== null) {
  56151. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  56152. }
  56153. this.update();
  56154. }
  56155. /**
  56156. * Tells the pipeline to update its post-processes
  56157. */
  56158. HDRRenderingPipeline.prototype.update = function () {
  56159. this._needUpdate = true;
  56160. };
  56161. /**
  56162. * Returns the current calculated luminance
  56163. */
  56164. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  56165. return this._hdrCurrentLuminance;
  56166. };
  56167. /**
  56168. * Returns the currently drawn luminance
  56169. */
  56170. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  56171. return this._hdrOutputLuminance;
  56172. };
  56173. /**
  56174. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  56175. */
  56176. HDRRenderingPipeline.prototype.dispose = function () {
  56177. this._originalPostProcess = undefined;
  56178. this._brightPassPostProcess = undefined;
  56179. this._downSampleX4PostProcess = undefined;
  56180. this._guassianBlurHPostProcess = undefined;
  56181. this._guassianBlurVPostProcess = undefined;
  56182. this._textureAdderPostProcess = undefined;
  56183. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  56184. this._downSamplePostProcesses[i] = undefined;
  56185. }
  56186. this._hdrPostProcess = undefined;
  56187. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  56188. };
  56189. /**
  56190. * Creates the HDR post-process and computes the luminance adaptation
  56191. */
  56192. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  56193. var _this = this;
  56194. var hdrLastLuminance = 0.0;
  56195. this._hdrOutputLuminance = -1.0;
  56196. this._hdrCurrentLuminance = 1.0;
  56197. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  56198. this._hdrPostProcess.onApply = function (effect) {
  56199. if (_this._hdrOutputLuminance < 0.0) {
  56200. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  56201. }
  56202. else {
  56203. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  56204. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  56205. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  56206. }
  56207. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  56208. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  56209. }
  56210. else {
  56211. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  56212. }
  56213. }
  56214. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  56215. hdrLastLuminance += scene.getEngine().getDeltaTime();
  56216. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  56217. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  56218. effect.setFloat("exposure", _this.exposure);
  56219. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  56220. _this._needUpdate = false;
  56221. };
  56222. };
  56223. /**
  56224. * Texture Adder post-process
  56225. */
  56226. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  56227. var _this = this;
  56228. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  56229. this._textureAdderPostProcess.onApply = function (effect) {
  56230. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  56231. };
  56232. };
  56233. /**
  56234. * Down sample X4 post-process
  56235. */
  56236. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  56237. var _this = this;
  56238. var downSampleX4Offsets = new Array(32);
  56239. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  56240. this._downSampleX4PostProcess.onApply = function (effect) {
  56241. if (_this._needUpdate) {
  56242. var id = 0;
  56243. for (var i = -2; i < 2; i++) {
  56244. for (var j = -2; j < 2; j++) {
  56245. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  56246. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  56247. id += 2;
  56248. }
  56249. }
  56250. }
  56251. effect.setArray2("dsOffsets", downSampleX4Offsets);
  56252. };
  56253. };
  56254. /**
  56255. * Bright pass post-process
  56256. */
  56257. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  56258. var _this = this;
  56259. var brightOffsets = new Array(8);
  56260. var brightPassCallback = function (effect) {
  56261. if (_this._needUpdate) {
  56262. var sU = (1.0 / _this._brightPassPostProcess.width);
  56263. var sV = (1.0 / _this._brightPassPostProcess.height);
  56264. brightOffsets[0] = -0.5 * sU;
  56265. brightOffsets[1] = 0.5 * sV;
  56266. brightOffsets[2] = 0.5 * sU;
  56267. brightOffsets[3] = 0.5 * sV;
  56268. brightOffsets[4] = -0.5 * sU;
  56269. brightOffsets[5] = -0.5 * sV;
  56270. brightOffsets[6] = 0.5 * sU;
  56271. brightOffsets[7] = -0.5 * sV;
  56272. }
  56273. effect.setArray2("dsOffsets", brightOffsets);
  56274. effect.setFloat("brightThreshold", _this.brightThreshold);
  56275. };
  56276. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  56277. this._brightPassPostProcess.onApply = brightPassCallback;
  56278. };
  56279. /**
  56280. * Luminance generator. Creates the luminance post-process and down sample post-processes
  56281. */
  56282. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  56283. var _this = this;
  56284. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  56285. var luminanceOffsets = new Array(8);
  56286. var downSampleOffsets = new Array(18);
  56287. var halfDestPixelSize;
  56288. this._downSamplePostProcesses = new Array(lumSteps);
  56289. // Utils for luminance
  56290. var luminanceUpdateSourceOffsets = function (width, height) {
  56291. var sU = (1.0 / width);
  56292. var sV = (1.0 / height);
  56293. luminanceOffsets[0] = -0.5 * sU;
  56294. luminanceOffsets[1] = 0.5 * sV;
  56295. luminanceOffsets[2] = 0.5 * sU;
  56296. luminanceOffsets[3] = 0.5 * sV;
  56297. luminanceOffsets[4] = -0.5 * sU;
  56298. luminanceOffsets[5] = -0.5 * sV;
  56299. luminanceOffsets[6] = 0.5 * sU;
  56300. luminanceOffsets[7] = -0.5 * sV;
  56301. };
  56302. var luminanceUpdateDestOffsets = function (width, height) {
  56303. var id = 0;
  56304. for (var x = -1; x < 2; x++) {
  56305. for (var y = -1; y < 2; y++) {
  56306. downSampleOffsets[id] = (x) / width;
  56307. downSampleOffsets[id + 1] = (y) / height;
  56308. id += 2;
  56309. }
  56310. }
  56311. };
  56312. // Luminance callback
  56313. var luminanceCallback = function (effect) {
  56314. if (_this._needUpdate) {
  56315. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  56316. }
  56317. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  56318. effect.setArray2("lumOffsets", luminanceOffsets);
  56319. };
  56320. // Down sample callbacks
  56321. var downSampleCallback = function (indice) {
  56322. var i = indice;
  56323. return function (effect) {
  56324. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  56325. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  56326. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  56327. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  56328. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  56329. effect.setArray2("dsOffsets", downSampleOffsets);
  56330. };
  56331. };
  56332. var downSampleAfterRenderCallback = function (effect) {
  56333. // Unpack result
  56334. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  56335. 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);
  56336. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  56337. };
  56338. // Create luminance post-process
  56339. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  56340. 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);
  56341. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  56342. // Create down sample post-processes
  56343. for (var i = lumSteps - 2; i >= 0; i--) {
  56344. var length = Math.pow(3, i);
  56345. ratio = { width: length, height: length };
  56346. var defines = "#define DOWN_SAMPLE\n";
  56347. if (i === 0) {
  56348. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  56349. }
  56350. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  56351. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  56352. if (i === 0) {
  56353. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  56354. }
  56355. }
  56356. };
  56357. /**
  56358. * Gaussian blur post-processes. Horizontal and Vertical
  56359. */
  56360. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  56361. var _this = this;
  56362. var blurOffsetsW = new Array(9);
  56363. var blurOffsetsH = new Array(9);
  56364. var blurWeights = new Array(9);
  56365. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  56366. // Utils for gaussian blur
  56367. var calculateBlurOffsets = function (height) {
  56368. var lastOutputDimensions = {
  56369. width: scene.getEngine().getRenderWidth(),
  56370. height: scene.getEngine().getRenderHeight()
  56371. };
  56372. for (var i = 0; i < 9; i++) {
  56373. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  56374. if (height) {
  56375. blurOffsetsH[i] = value;
  56376. }
  56377. else {
  56378. blurOffsetsW[i] = value;
  56379. }
  56380. }
  56381. };
  56382. var calculateWeights = function () {
  56383. var x = 0.0;
  56384. for (var i = 0; i < 9; i++) {
  56385. x = (i - 4.0) / 4.0;
  56386. 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));
  56387. }
  56388. };
  56389. // Callback
  56390. var gaussianBlurCallback = function (height) {
  56391. return function (effect) {
  56392. if (_this._needUpdate) {
  56393. calculateWeights();
  56394. calculateBlurOffsets(height);
  56395. }
  56396. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  56397. effect.setArray("blurWeights", blurWeights);
  56398. effect.setFloat("multiplier", _this.gaussMultiplier);
  56399. };
  56400. };
  56401. // Create horizontal gaussian blur post-processes
  56402. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  56403. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  56404. // Create vertical gaussian blur post-process
  56405. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  56406. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  56407. };
  56408. // Luminance generator
  56409. HDRRenderingPipeline.LUM_STEPS = 6;
  56410. return HDRRenderingPipeline;
  56411. }(BABYLON.PostProcessRenderPipeline));
  56412. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  56413. })(BABYLON || (BABYLON = {}));
  56414. var BABYLON;
  56415. (function (BABYLON) {
  56416. var FaceAdjacencies = (function () {
  56417. function FaceAdjacencies() {
  56418. this.edges = new Array();
  56419. this.edgesConnectedCount = 0;
  56420. }
  56421. return FaceAdjacencies;
  56422. }());
  56423. var EdgesRenderer = (function () {
  56424. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  56425. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  56426. if (epsilon === void 0) { epsilon = 0.95; }
  56427. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  56428. this.edgesWidthScalerForOrthographic = 1000.0;
  56429. this.edgesWidthScalerForPerspective = 50.0;
  56430. this._linesPositions = new Array();
  56431. this._linesNormals = new Array();
  56432. this._linesIndices = new Array();
  56433. this._buffers = {};
  56434. this._checkVerticesInsteadOfIndices = false;
  56435. this._source = source;
  56436. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  56437. this._epsilon = epsilon;
  56438. this._prepareRessources();
  56439. this._generateEdgesLines();
  56440. }
  56441. EdgesRenderer.prototype._prepareRessources = function () {
  56442. if (this._lineShader) {
  56443. return;
  56444. }
  56445. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  56446. attributes: ["position", "normal"],
  56447. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  56448. });
  56449. this._lineShader.disableDepthWrite = true;
  56450. this._lineShader.backFaceCulling = false;
  56451. };
  56452. EdgesRenderer.prototype.dispose = function () {
  56453. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  56454. if (buffer) {
  56455. buffer.dispose();
  56456. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  56457. }
  56458. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  56459. if (buffer) {
  56460. buffer.dispose();
  56461. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  56462. }
  56463. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  56464. this._lineShader.dispose();
  56465. };
  56466. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  56467. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  56468. return 0;
  56469. }
  56470. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  56471. return 1;
  56472. }
  56473. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  56474. return 2;
  56475. }
  56476. return -1;
  56477. };
  56478. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  56479. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  56480. return 0;
  56481. }
  56482. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  56483. return 1;
  56484. }
  56485. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  56486. return 2;
  56487. }
  56488. return -1;
  56489. };
  56490. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  56491. var needToCreateLine;
  56492. if (edge === undefined) {
  56493. needToCreateLine = true;
  56494. }
  56495. else {
  56496. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  56497. needToCreateLine = dotProduct < this._epsilon;
  56498. }
  56499. if (needToCreateLine) {
  56500. var offset = this._linesPositions.length / 3;
  56501. var normal = p0.subtract(p1);
  56502. normal.normalize();
  56503. // Positions
  56504. this._linesPositions.push(p0.x);
  56505. this._linesPositions.push(p0.y);
  56506. this._linesPositions.push(p0.z);
  56507. this._linesPositions.push(p0.x);
  56508. this._linesPositions.push(p0.y);
  56509. this._linesPositions.push(p0.z);
  56510. this._linesPositions.push(p1.x);
  56511. this._linesPositions.push(p1.y);
  56512. this._linesPositions.push(p1.z);
  56513. this._linesPositions.push(p1.x);
  56514. this._linesPositions.push(p1.y);
  56515. this._linesPositions.push(p1.z);
  56516. // Normals
  56517. this._linesNormals.push(p1.x);
  56518. this._linesNormals.push(p1.y);
  56519. this._linesNormals.push(p1.z);
  56520. this._linesNormals.push(-1);
  56521. this._linesNormals.push(p1.x);
  56522. this._linesNormals.push(p1.y);
  56523. this._linesNormals.push(p1.z);
  56524. this._linesNormals.push(1);
  56525. this._linesNormals.push(p0.x);
  56526. this._linesNormals.push(p0.y);
  56527. this._linesNormals.push(p0.z);
  56528. this._linesNormals.push(-1);
  56529. this._linesNormals.push(p0.x);
  56530. this._linesNormals.push(p0.y);
  56531. this._linesNormals.push(p0.z);
  56532. this._linesNormals.push(1);
  56533. // Indices
  56534. this._linesIndices.push(offset);
  56535. this._linesIndices.push(offset + 1);
  56536. this._linesIndices.push(offset + 2);
  56537. this._linesIndices.push(offset);
  56538. this._linesIndices.push(offset + 2);
  56539. this._linesIndices.push(offset + 3);
  56540. }
  56541. };
  56542. EdgesRenderer.prototype._generateEdgesLines = function () {
  56543. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56544. var indices = this._source.getIndices();
  56545. // First let's find adjacencies
  56546. var adjacencies = new Array();
  56547. var faceNormals = new Array();
  56548. var index;
  56549. var faceAdjacencies;
  56550. // Prepare faces
  56551. for (index = 0; index < indices.length; index += 3) {
  56552. faceAdjacencies = new FaceAdjacencies();
  56553. var p0Index = indices[index];
  56554. var p1Index = indices[index + 1];
  56555. var p2Index = indices[index + 2];
  56556. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  56557. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  56558. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  56559. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  56560. faceNormal.normalize();
  56561. faceNormals.push(faceNormal);
  56562. adjacencies.push(faceAdjacencies);
  56563. }
  56564. // Scan
  56565. for (index = 0; index < adjacencies.length; index++) {
  56566. faceAdjacencies = adjacencies[index];
  56567. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  56568. var otherFaceAdjacencies = adjacencies[otherIndex];
  56569. if (faceAdjacencies.edgesConnectedCount === 3) {
  56570. break;
  56571. }
  56572. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  56573. continue;
  56574. }
  56575. var otherP0 = indices[otherIndex * 3];
  56576. var otherP1 = indices[otherIndex * 3 + 1];
  56577. var otherP2 = indices[otherIndex * 3 + 2];
  56578. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  56579. var otherEdgeIndex;
  56580. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  56581. continue;
  56582. }
  56583. switch (edgeIndex) {
  56584. case 0:
  56585. if (this._checkVerticesInsteadOfIndices) {
  56586. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56587. }
  56588. else {
  56589. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  56590. }
  56591. break;
  56592. case 1:
  56593. if (this._checkVerticesInsteadOfIndices) {
  56594. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56595. }
  56596. else {
  56597. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  56598. }
  56599. break;
  56600. case 2:
  56601. if (this._checkVerticesInsteadOfIndices) {
  56602. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  56603. }
  56604. else {
  56605. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  56606. }
  56607. break;
  56608. }
  56609. if (otherEdgeIndex === -1) {
  56610. continue;
  56611. }
  56612. faceAdjacencies.edges[edgeIndex] = otherIndex;
  56613. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  56614. faceAdjacencies.edgesConnectedCount++;
  56615. otherFaceAdjacencies.edgesConnectedCount++;
  56616. if (faceAdjacencies.edgesConnectedCount === 3) {
  56617. break;
  56618. }
  56619. }
  56620. }
  56621. }
  56622. // Create lines
  56623. for (index = 0; index < adjacencies.length; index++) {
  56624. // 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
  56625. var current = adjacencies[index];
  56626. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  56627. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  56628. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  56629. }
  56630. // Merge into a single mesh
  56631. var engine = this._source.getScene().getEngine();
  56632. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  56633. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  56634. this._ib = engine.createIndexBuffer(this._linesIndices);
  56635. this._indicesCount = this._linesIndices.length;
  56636. };
  56637. EdgesRenderer.prototype.render = function () {
  56638. if (!this._lineShader.isReady()) {
  56639. return;
  56640. }
  56641. var scene = this._source.getScene();
  56642. var engine = scene.getEngine();
  56643. this._lineShader._preBind();
  56644. // VBOs
  56645. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  56646. scene.resetCachedMaterial();
  56647. this._lineShader.setColor4("color", this._source.edgesColor);
  56648. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  56649. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  56650. }
  56651. else {
  56652. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  56653. }
  56654. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  56655. this._lineShader.bind(this._source.getWorldMatrix());
  56656. // Draw order
  56657. engine.draw(true, 0, this._indicesCount);
  56658. this._lineShader.unbind();
  56659. engine.setDepthWrite(true);
  56660. };
  56661. return EdgesRenderer;
  56662. }());
  56663. BABYLON.EdgesRenderer = EdgesRenderer;
  56664. })(BABYLON || (BABYLON = {}));
  56665. var BABYLON;
  56666. (function (BABYLON) {
  56667. (function (TonemappingOperator) {
  56668. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  56669. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  56670. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  56671. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  56672. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  56673. var TonemappingOperator = BABYLON.TonemappingOperator;
  56674. ;
  56675. var TonemapPostProcess = (function (_super) {
  56676. __extends(TonemapPostProcess, _super);
  56677. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  56678. var _this = this;
  56679. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  56680. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  56681. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  56682. this._operator = _operator;
  56683. this.exposureAdjustment = exposureAdjustment;
  56684. var defines = "#define ";
  56685. if (this._operator === TonemappingOperator.Hable)
  56686. defines += "HABLE_TONEMAPPING";
  56687. else if (this._operator === TonemappingOperator.Reinhard)
  56688. defines += "REINHARD_TONEMAPPING";
  56689. else if (this._operator === TonemappingOperator.HejiDawson)
  56690. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  56691. else if (this._operator === TonemappingOperator.Photographic)
  56692. defines += "PHOTOGRAPHIC_TONEMAPPING";
  56693. //sadly a second call to create the effect.
  56694. this.updateEffect(defines);
  56695. this.onApply = function (effect) {
  56696. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  56697. };
  56698. }
  56699. return TonemapPostProcess;
  56700. }(BABYLON.PostProcess));
  56701. BABYLON.TonemapPostProcess = TonemapPostProcess;
  56702. })(BABYLON || (BABYLON = {}));
  56703. var BABYLON;
  56704. (function (BABYLON) {
  56705. var ReflectionProbe = (function () {
  56706. function ReflectionProbe(name, size, scene, generateMipMaps) {
  56707. var _this = this;
  56708. if (generateMipMaps === void 0) { generateMipMaps = true; }
  56709. this.name = name;
  56710. this._viewMatrix = BABYLON.Matrix.Identity();
  56711. this._target = BABYLON.Vector3.Zero();
  56712. this._add = BABYLON.Vector3.Zero();
  56713. this.invertYAxis = false;
  56714. this.position = BABYLON.Vector3.Zero();
  56715. this._scene = scene;
  56716. this._scene.reflectionProbes.push(this);
  56717. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  56718. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  56719. switch (faceIndex) {
  56720. case 0:
  56721. _this._add.copyFromFloats(1, 0, 0);
  56722. break;
  56723. case 1:
  56724. _this._add.copyFromFloats(-1, 0, 0);
  56725. break;
  56726. case 2:
  56727. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  56728. break;
  56729. case 3:
  56730. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  56731. break;
  56732. case 4:
  56733. _this._add.copyFromFloats(0, 0, 1);
  56734. break;
  56735. case 5:
  56736. _this._add.copyFromFloats(0, 0, -1);
  56737. break;
  56738. }
  56739. if (_this._attachedMesh) {
  56740. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  56741. }
  56742. _this.position.addToRef(_this._add, _this._target);
  56743. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  56744. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  56745. });
  56746. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  56747. scene.updateTransformMatrix(true);
  56748. });
  56749. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  56750. }
  56751. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  56752. get: function () {
  56753. return this._renderTargetTexture.refreshRate;
  56754. },
  56755. set: function (value) {
  56756. this._renderTargetTexture.refreshRate = value;
  56757. },
  56758. enumerable: true,
  56759. configurable: true
  56760. });
  56761. ReflectionProbe.prototype.getScene = function () {
  56762. return this._scene;
  56763. };
  56764. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  56765. get: function () {
  56766. return this._renderTargetTexture;
  56767. },
  56768. enumerable: true,
  56769. configurable: true
  56770. });
  56771. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  56772. get: function () {
  56773. return this._renderTargetTexture.renderList;
  56774. },
  56775. enumerable: true,
  56776. configurable: true
  56777. });
  56778. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  56779. this._attachedMesh = mesh;
  56780. };
  56781. ReflectionProbe.prototype.dispose = function () {
  56782. var index = this._scene.reflectionProbes.indexOf(this);
  56783. if (index !== -1) {
  56784. // Remove from the scene if found
  56785. this._scene.reflectionProbes.splice(index, 1);
  56786. }
  56787. if (this._renderTargetTexture) {
  56788. this._renderTargetTexture.dispose();
  56789. this._renderTargetTexture = null;
  56790. }
  56791. };
  56792. return ReflectionProbe;
  56793. }());
  56794. BABYLON.ReflectionProbe = ReflectionProbe;
  56795. })(BABYLON || (BABYLON = {}));
  56796. var BABYLON;
  56797. (function (BABYLON) {
  56798. var SolidParticle = (function () {
  56799. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape) {
  56800. this.color = new BABYLON.Color4(1, 1, 1, 1); // color
  56801. this.position = BABYLON.Vector3.Zero(); // position
  56802. this.rotation = BABYLON.Vector3.Zero(); // rotation
  56803. this.scaling = new BABYLON.Vector3(1, 1, 1); // scaling
  56804. this.uvs = new BABYLON.Vector4(0, 0, 1, 1); // uvs
  56805. this.velocity = BABYLON.Vector3.Zero(); // velocity
  56806. this.alive = true; // alive
  56807. this.isVisible = true; // visibility
  56808. this.idx = particleIndex;
  56809. this._pos = positionIndex;
  56810. this._model = model;
  56811. this.shapeId = shapeId;
  56812. this.idxInShape = idxInShape;
  56813. }
  56814. Object.defineProperty(SolidParticle.prototype, "scale", {
  56815. //legacy support, changed scale to scaling
  56816. get: function () {
  56817. return this.scaling;
  56818. },
  56819. set: function (scale) {
  56820. this.scaling = scale;
  56821. },
  56822. enumerable: true,
  56823. configurable: true
  56824. });
  56825. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  56826. //legacy support, changed quaternion to rotationQuaternion
  56827. get: function () {
  56828. return this.rotationQuaternion;
  56829. },
  56830. set: function (q) {
  56831. this.rotationQuaternion = q;
  56832. },
  56833. enumerable: true,
  56834. configurable: true
  56835. });
  56836. return SolidParticle;
  56837. }());
  56838. BABYLON.SolidParticle = SolidParticle;
  56839. var ModelShape = (function () {
  56840. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  56841. this.shapeID = id;
  56842. this._shape = shape;
  56843. this._shapeUV = shapeUV;
  56844. this._positionFunction = posFunction;
  56845. this._vertexFunction = vtxFunction;
  56846. }
  56847. return ModelShape;
  56848. }());
  56849. BABYLON.ModelShape = ModelShape;
  56850. })(BABYLON || (BABYLON = {}));
  56851. var BABYLON;
  56852. (function (BABYLON) {
  56853. /**
  56854. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  56855. */
  56856. var SolidParticleSystem = (function () {
  56857. /**
  56858. * Creates a SPS (Solid Particle System) object.
  56859. * `name` (String) is the SPS name, this will be the underlying mesh name.
  56860. * `scene` (Scene) is the scene in which the SPS is added.
  56861. * `updatable` (default true) : if the SPS must be updatable or immutable.
  56862. * `isPickable` (default false) : if the solid particles must be pickable.
  56863. */
  56864. function SolidParticleSystem(name, scene, options) {
  56865. // public members
  56866. /**
  56867. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  56868. * Example : var p = SPS.particles[i];
  56869. */
  56870. this.particles = new Array();
  56871. /**
  56872. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  56873. */
  56874. this.nbParticles = 0;
  56875. /**
  56876. * If the particles must ever face the camera (default false). Useful for planar particles.
  56877. */
  56878. this.billboard = false;
  56879. /**
  56880. * This a counter ofr your own usage. It's not set by any SPS functions.
  56881. */
  56882. this.counter = 0;
  56883. /**
  56884. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  56885. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  56886. */
  56887. this.vars = {};
  56888. this._positions = new Array();
  56889. this._indices = new Array();
  56890. this._normals = new Array();
  56891. this._colors = new Array();
  56892. this._uvs = new Array();
  56893. this._index = 0; // indices index
  56894. this._updatable = true;
  56895. this._pickable = false;
  56896. this._isVisibilityBoxLocked = false;
  56897. this._alwaysVisible = false;
  56898. this._shapeCounter = 0;
  56899. this._copy = new BABYLON.SolidParticle(null, null, null, null, null);
  56900. this._color = new BABYLON.Color4(0, 0, 0, 0);
  56901. this._computeParticleColor = true;
  56902. this._computeParticleTexture = true;
  56903. this._computeParticleRotation = true;
  56904. this._computeParticleVertex = false;
  56905. this._computeBoundingBox = false;
  56906. this._cam_axisZ = BABYLON.Vector3.Zero();
  56907. this._cam_axisY = BABYLON.Vector3.Zero();
  56908. this._cam_axisX = BABYLON.Vector3.Zero();
  56909. this._axisX = BABYLON.Axis.X;
  56910. this._axisY = BABYLON.Axis.Y;
  56911. this._axisZ = BABYLON.Axis.Z;
  56912. this._camDir = BABYLON.Vector3.Zero();
  56913. this._rotMatrix = new BABYLON.Matrix();
  56914. this._invertMatrix = new BABYLON.Matrix();
  56915. this._rotated = BABYLON.Vector3.Zero();
  56916. this._quaternion = new BABYLON.Quaternion();
  56917. this._vertex = BABYLON.Vector3.Zero();
  56918. this._normal = BABYLON.Vector3.Zero();
  56919. this._yaw = 0.0;
  56920. this._pitch = 0.0;
  56921. this._roll = 0.0;
  56922. this._halfroll = 0.0;
  56923. this._halfpitch = 0.0;
  56924. this._halfyaw = 0.0;
  56925. this._sinRoll = 0.0;
  56926. this._cosRoll = 0.0;
  56927. this._sinPitch = 0.0;
  56928. this._cosPitch = 0.0;
  56929. this._sinYaw = 0.0;
  56930. this._cosYaw = 0.0;
  56931. this._w = 0.0;
  56932. this._minimum = BABYLON.Tmp.Vector3[0];
  56933. this._maximum = BABYLON.Tmp.Vector3[1];
  56934. this.name = name;
  56935. this._scene = scene;
  56936. this._camera = scene.activeCamera;
  56937. this._pickable = options ? options.isPickable : false;
  56938. if (options && options.updatable) {
  56939. this._updatable = options.updatable;
  56940. }
  56941. else {
  56942. this._updatable = true;
  56943. }
  56944. if (this._pickable) {
  56945. this.pickedParticles = [];
  56946. }
  56947. }
  56948. /**
  56949. * Builds the SPS underlying mesh. Returns a standard Mesh.
  56950. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  56951. */
  56952. SolidParticleSystem.prototype.buildMesh = function () {
  56953. if (this.nbParticles === 0) {
  56954. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  56955. this.addShape(triangle, 1);
  56956. triangle.dispose();
  56957. }
  56958. this._positions32 = new Float32Array(this._positions);
  56959. this._uvs32 = new Float32Array(this._uvs);
  56960. this._colors32 = new Float32Array(this._colors);
  56961. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  56962. this._normals32 = new Float32Array(this._normals);
  56963. this._fixedNormal32 = new Float32Array(this._normals);
  56964. var vertexData = new BABYLON.VertexData();
  56965. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  56966. vertexData.indices = this._indices;
  56967. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  56968. if (this._uvs32) {
  56969. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  56970. ;
  56971. }
  56972. if (this._colors32) {
  56973. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  56974. }
  56975. var mesh = new BABYLON.Mesh(this.name, this._scene);
  56976. vertexData.applyToMesh(mesh, this._updatable);
  56977. this.mesh = mesh;
  56978. this.mesh.isPickable = this._pickable;
  56979. // free memory
  56980. this._positions = null;
  56981. this._normals = null;
  56982. this._uvs = null;
  56983. this._colors = null;
  56984. if (!this._updatable) {
  56985. this.particles.length = 0;
  56986. }
  56987. return mesh;
  56988. };
  56989. /**
  56990. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  56991. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  56992. * Thus the particles generated from `digest()` have their property `position` set yet.
  56993. * `mesh` ( Mesh ) is the mesh to be digested
  56994. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  56995. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  56996. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  56997. */
  56998. SolidParticleSystem.prototype.digest = function (mesh, options) {
  56999. var size = (options && options.facetNb) || 1;
  57000. var number = (options && options.number);
  57001. var delta = (options && options.delta) || 0;
  57002. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57003. var meshInd = mesh.getIndices();
  57004. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57005. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57006. var f = 0; // facet counter
  57007. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57008. // compute size from number
  57009. if (number) {
  57010. number = (number > totalFacets) ? totalFacets : number;
  57011. size = Math.round(totalFacets / number);
  57012. delta = 0;
  57013. }
  57014. else {
  57015. size = (size > totalFacets) ? totalFacets : size;
  57016. }
  57017. var facetPos = []; // submesh positions
  57018. var facetInd = []; // submesh indices
  57019. var facetUV = []; // submesh UV
  57020. var facetCol = []; // submesh colors
  57021. var barycenter = BABYLON.Tmp.Vector3[0];
  57022. var rand;
  57023. var sizeO = size;
  57024. while (f < totalFacets) {
  57025. size = sizeO + Math.floor((1 + delta) * Math.random());
  57026. if (f > totalFacets - size) {
  57027. size = totalFacets - f;
  57028. }
  57029. // reset temp arrays
  57030. facetPos.length = 0;
  57031. facetInd.length = 0;
  57032. facetUV.length = 0;
  57033. facetCol.length = 0;
  57034. // iterate over "size" facets
  57035. var fi = 0;
  57036. for (var j = f * 3; j < (f + size) * 3; j++) {
  57037. facetInd.push(fi);
  57038. var i = meshInd[j];
  57039. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57040. if (meshUV) {
  57041. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57042. }
  57043. if (meshCol) {
  57044. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57045. }
  57046. fi++;
  57047. }
  57048. // create a model shape for each single particle
  57049. var idx = this.nbParticles;
  57050. var shape = this._posToShape(facetPos);
  57051. var shapeUV = this._uvsToShapeUV(facetUV);
  57052. // compute the barycenter of the shape
  57053. var v;
  57054. for (v = 0; v < shape.length; v++) {
  57055. barycenter.addInPlace(shape[v]);
  57056. }
  57057. barycenter.scaleInPlace(1 / shape.length);
  57058. // shift the shape from its barycenter to the origin
  57059. for (v = 0; v < shape.length; v++) {
  57060. shape[v].subtractInPlace(barycenter);
  57061. }
  57062. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  57063. // add the particle in the SPS
  57064. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, idx, 0, null);
  57065. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0);
  57066. // initialize the particle position
  57067. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57068. this._index += shape.length;
  57069. idx++;
  57070. this.nbParticles++;
  57071. this._shapeCounter++;
  57072. f += size;
  57073. }
  57074. return this;
  57075. };
  57076. //reset copy
  57077. SolidParticleSystem.prototype._resetCopy = function () {
  57078. this._copy.position.x = 0;
  57079. this._copy.position.y = 0;
  57080. this._copy.position.z = 0;
  57081. this._copy.rotation.x = 0;
  57082. this._copy.rotation.y = 0;
  57083. this._copy.rotation.z = 0;
  57084. this._copy.rotationQuaternion = null;
  57085. this._copy.scaling.x = 1;
  57086. this._copy.scaling.y = 1;
  57087. this._copy.scaling.z = 1;
  57088. this._copy.uvs.x = 0;
  57089. this._copy.uvs.y = 0;
  57090. this._copy.uvs.z = 1;
  57091. this._copy.uvs.w = 1;
  57092. this._copy.color = null;
  57093. };
  57094. // _meshBuilder : inserts the shape model in the global SPS mesh
  57095. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, idx, idxInShape, options) {
  57096. var i;
  57097. var u = 0;
  57098. var c = 0;
  57099. this._resetCopy();
  57100. if (options && options.positionFunction) {
  57101. options.positionFunction(this._copy, idx, idxInShape);
  57102. }
  57103. if (this._copy.rotationQuaternion) {
  57104. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57105. }
  57106. else {
  57107. this._yaw = this._copy.rotation.y;
  57108. this._pitch = this._copy.rotation.x;
  57109. this._roll = this._copy.rotation.z;
  57110. this._quaternionRotationYPR();
  57111. }
  57112. this._quaternionToRotationMatrix();
  57113. for (i = 0; i < shape.length; i++) {
  57114. this._vertex.x = shape[i].x;
  57115. this._vertex.y = shape[i].y;
  57116. this._vertex.z = shape[i].z;
  57117. if (options && options.vertexFunction) {
  57118. options.vertexFunction(this._copy, this._vertex, i);
  57119. }
  57120. this._vertex.x *= this._copy.scaling.x;
  57121. this._vertex.y *= this._copy.scaling.y;
  57122. this._vertex.z *= this._copy.scaling.z;
  57123. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57124. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57125. if (meshUV) {
  57126. 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);
  57127. u += 2;
  57128. }
  57129. if (this._copy.color) {
  57130. this._color = this._copy.color;
  57131. }
  57132. else if (meshCol && meshCol[c] !== undefined) {
  57133. this._color.r = meshCol[c];
  57134. this._color.g = meshCol[c + 1];
  57135. this._color.b = meshCol[c + 2];
  57136. this._color.a = meshCol[c + 3];
  57137. }
  57138. else {
  57139. this._color.r = 1;
  57140. this._color.g = 1;
  57141. this._color.b = 1;
  57142. this._color.a = 1;
  57143. }
  57144. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57145. c += 4;
  57146. }
  57147. for (i = 0; i < meshInd.length; i++) {
  57148. indices.push(p + meshInd[i]);
  57149. }
  57150. if (this._pickable) {
  57151. var nbfaces = meshInd.length / 3;
  57152. for (i = 0; i < nbfaces; i++) {
  57153. this.pickedParticles.push({ idx: idx, faceId: i });
  57154. }
  57155. }
  57156. };
  57157. // returns a shape array from positions array
  57158. SolidParticleSystem.prototype._posToShape = function (positions) {
  57159. var shape = [];
  57160. for (var i = 0; i < positions.length; i += 3) {
  57161. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57162. }
  57163. return shape;
  57164. };
  57165. // returns a shapeUV array from a Vector4 uvs
  57166. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  57167. var shapeUV = [];
  57168. if (uvs) {
  57169. for (var i = 0; i < uvs.length; i++)
  57170. shapeUV.push(uvs[i]);
  57171. }
  57172. return shapeUV;
  57173. };
  57174. // adds a new particle object in the particles array
  57175. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape) {
  57176. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape));
  57177. };
  57178. /**
  57179. * Adds some particles to the SPS from the model shape. Returns the shape id.
  57180. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  57181. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  57182. * `nb` (positive integer) the number of particles to be created from this model
  57183. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  57184. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  57185. */
  57186. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  57187. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57188. var meshInd = mesh.getIndices();
  57189. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57190. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57191. var shape = this._posToShape(meshPos);
  57192. var shapeUV = this._uvsToShapeUV(meshUV);
  57193. var posfunc = options ? options.positionFunction : null;
  57194. var vtxfunc = options ? options.vertexFunction : null;
  57195. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  57196. // particles
  57197. var idx = this.nbParticles;
  57198. for (var i = 0; i < nb; i++) {
  57199. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, idx, i, options);
  57200. if (this._updatable) {
  57201. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i);
  57202. }
  57203. this._index += shape.length;
  57204. idx++;
  57205. }
  57206. this.nbParticles += nb;
  57207. this._shapeCounter++;
  57208. return this._shapeCounter - 1;
  57209. };
  57210. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  57211. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  57212. this._resetCopy();
  57213. if (particle._model._positionFunction) {
  57214. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  57215. }
  57216. if (this._copy.rotationQuaternion) {
  57217. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57218. }
  57219. else {
  57220. this._yaw = this._copy.rotation.y;
  57221. this._pitch = this._copy.rotation.x;
  57222. this._roll = this._copy.rotation.z;
  57223. this._quaternionRotationYPR();
  57224. }
  57225. this._quaternionToRotationMatrix();
  57226. this._shape = particle._model._shape;
  57227. for (var pt = 0; pt < this._shape.length; pt++) {
  57228. this._vertex.x = this._shape[pt].x;
  57229. this._vertex.y = this._shape[pt].y;
  57230. this._vertex.z = this._shape[pt].z;
  57231. if (particle._model._vertexFunction) {
  57232. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  57233. }
  57234. this._vertex.x *= this._copy.scaling.x;
  57235. this._vertex.y *= this._copy.scaling.y;
  57236. this._vertex.z *= this._copy.scaling.z;
  57237. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57238. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  57239. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  57240. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  57241. }
  57242. particle.position.x = 0;
  57243. particle.position.y = 0;
  57244. particle.position.z = 0;
  57245. particle.rotation.x = 0;
  57246. particle.rotation.y = 0;
  57247. particle.rotation.z = 0;
  57248. particle.rotationQuaternion = null;
  57249. particle.scaling.x = 1;
  57250. particle.scaling.y = 1;
  57251. particle.scaling.z = 1;
  57252. };
  57253. /**
  57254. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  57255. */
  57256. SolidParticleSystem.prototype.rebuildMesh = function () {
  57257. for (var p = 0; p < this.particles.length; p++) {
  57258. this._rebuildParticle(this.particles[p]);
  57259. }
  57260. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57261. };
  57262. /**
  57263. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  57264. * This method calls `updateParticle()` for each particle of the SPS.
  57265. * For an animated SPS, it is usually called within the render loop.
  57266. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  57267. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  57268. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  57269. */
  57270. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  57271. if (start === void 0) { start = 0; }
  57272. if (end === void 0) { end = this.nbParticles - 1; }
  57273. if (update === void 0) { update = true; }
  57274. if (!this._updatable) {
  57275. return;
  57276. }
  57277. // custom beforeUpdate
  57278. this.beforeUpdateParticles(start, end, update);
  57279. this._cam_axisX.x = 1.0;
  57280. this._cam_axisX.y = 0.0;
  57281. this._cam_axisX.z = 0.0;
  57282. this._cam_axisY.x = 0.0;
  57283. this._cam_axisY.y = 1.0;
  57284. this._cam_axisY.z = 0.0;
  57285. this._cam_axisZ.x = 0.0;
  57286. this._cam_axisZ.y = 0.0;
  57287. this._cam_axisZ.z = 1.0;
  57288. // if the particles will always face the camera
  57289. if (this.billboard) {
  57290. // compute the camera position and un-rotate it by the current mesh rotation
  57291. this._yaw = this.mesh.rotation.y;
  57292. this._pitch = this.mesh.rotation.x;
  57293. this._roll = this.mesh.rotation.z;
  57294. this._quaternionRotationYPR();
  57295. this._quaternionToRotationMatrix();
  57296. this._rotMatrix.invertToRef(this._invertMatrix);
  57297. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  57298. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  57299. this._cam_axisZ.normalize();
  57300. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  57301. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  57302. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  57303. this._cam_axisY.normalize();
  57304. this._cam_axisX.normalize();
  57305. }
  57306. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  57307. var idx = 0;
  57308. var index = 0;
  57309. var colidx = 0;
  57310. var colorIndex = 0;
  57311. var uvidx = 0;
  57312. var uvIndex = 0;
  57313. var pt = 0;
  57314. if (this._computeBoundingBox) {
  57315. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  57316. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  57317. }
  57318. // particle loop
  57319. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  57320. for (var p = start; p <= end; p++) {
  57321. this._particle = this.particles[p];
  57322. this._shape = this._particle._model._shape;
  57323. this._shapeUV = this._particle._model._shapeUV;
  57324. // call to custom user function to update the particle properties
  57325. this.updateParticle(this._particle);
  57326. if (this._particle.isVisible) {
  57327. // particle rotation matrix
  57328. if (this.billboard) {
  57329. this._particle.rotation.x = 0.0;
  57330. this._particle.rotation.y = 0.0;
  57331. }
  57332. if (this._computeParticleRotation || this.billboard) {
  57333. if (this._particle.rotationQuaternion) {
  57334. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57335. }
  57336. else {
  57337. this._yaw = this._particle.rotation.y;
  57338. this._pitch = this._particle.rotation.x;
  57339. this._roll = this._particle.rotation.z;
  57340. this._quaternionRotationYPR();
  57341. }
  57342. this._quaternionToRotationMatrix();
  57343. }
  57344. // particle vertex loop
  57345. for (pt = 0; pt < this._shape.length; pt++) {
  57346. idx = index + pt * 3;
  57347. colidx = colorIndex + pt * 4;
  57348. uvidx = uvIndex + pt * 2;
  57349. this._vertex.x = this._shape[pt].x;
  57350. this._vertex.y = this._shape[pt].y;
  57351. this._vertex.z = this._shape[pt].z;
  57352. if (this._computeParticleVertex) {
  57353. this.updateParticleVertex(this._particle, this._vertex, pt);
  57354. }
  57355. // positions
  57356. this._vertex.x *= this._particle.scaling.x;
  57357. this._vertex.y *= this._particle.scaling.y;
  57358. this._vertex.z *= this._particle.scaling.z;
  57359. 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];
  57360. 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;
  57361. 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;
  57362. 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;
  57363. 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;
  57364. 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;
  57365. 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;
  57366. if (this._computeBoundingBox) {
  57367. if (this._positions32[idx] < this._minimum.x) {
  57368. this._minimum.x = this._positions32[idx];
  57369. }
  57370. if (this._positions32[idx] > this._maximum.x) {
  57371. this._maximum.x = this._positions32[idx];
  57372. }
  57373. if (this._positions32[idx + 1] < this._minimum.y) {
  57374. this._minimum.y = this._positions32[idx + 1];
  57375. }
  57376. if (this._positions32[idx + 1] > this._maximum.y) {
  57377. this._maximum.y = this._positions32[idx + 1];
  57378. }
  57379. if (this._positions32[idx + 2] < this._minimum.z) {
  57380. this._minimum.z = this._positions32[idx + 2];
  57381. }
  57382. if (this._positions32[idx + 2] > this._maximum.z) {
  57383. this._maximum.z = this._positions32[idx + 2];
  57384. }
  57385. }
  57386. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  57387. if (!this._computeParticleVertex) {
  57388. this._normal.x = this._fixedNormal32[idx];
  57389. this._normal.y = this._fixedNormal32[idx + 1];
  57390. this._normal.z = this._fixedNormal32[idx + 2];
  57391. 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];
  57392. 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;
  57393. 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;
  57394. 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;
  57395. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  57396. 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;
  57397. 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;
  57398. }
  57399. if (this._computeParticleColor) {
  57400. this._colors32[colidx] = this._particle.color.r;
  57401. this._colors32[colidx + 1] = this._particle.color.g;
  57402. this._colors32[colidx + 2] = this._particle.color.b;
  57403. this._colors32[colidx + 3] = this._particle.color.a;
  57404. }
  57405. if (this._computeParticleTexture) {
  57406. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57407. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57408. }
  57409. }
  57410. }
  57411. else {
  57412. for (pt = 0; pt < this._shape.length; pt++) {
  57413. idx = index + pt * 3;
  57414. colidx = colorIndex + pt * 4;
  57415. uvidx = uvIndex + pt * 2;
  57416. this._positions32[idx] = this._camera.position.x;
  57417. this._positions32[idx + 1] = this._camera.position.y;
  57418. this._positions32[idx + 2] = this._camera.position.z;
  57419. this._normals32[idx] = 0.0;
  57420. this._normals32[idx + 1] = 0.0;
  57421. this._normals32[idx + 2] = 0.0;
  57422. if (this._computeParticleColor) {
  57423. this._colors32[colidx] = this._particle.color.r;
  57424. this._colors32[colidx + 1] = this._particle.color.g;
  57425. this._colors32[colidx + 2] = this._particle.color.b;
  57426. this._colors32[colidx + 3] = this._particle.color.a;
  57427. }
  57428. if (this._computeParticleTexture) {
  57429. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  57430. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  57431. }
  57432. }
  57433. }
  57434. // increment indexes for the next particle
  57435. index = idx + 3;
  57436. colorIndex = colidx + 4;
  57437. uvIndex = uvidx + 2;
  57438. }
  57439. // if the VBO must be updated
  57440. if (update) {
  57441. if (this._computeParticleColor) {
  57442. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  57443. }
  57444. if (this._computeParticleTexture) {
  57445. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  57446. }
  57447. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  57448. if (!this.mesh.areNormalsFrozen) {
  57449. if (this._computeParticleVertex) {
  57450. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  57451. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  57452. for (var i = 0; i < this._normals32.length; i++) {
  57453. this._fixedNormal32[i] = this._normals32[i];
  57454. }
  57455. }
  57456. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  57457. }
  57458. }
  57459. if (this._computeBoundingBox) {
  57460. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  57461. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  57462. }
  57463. this.afterUpdateParticles(start, end, update);
  57464. };
  57465. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  57466. this._halfroll = this._roll * 0.5;
  57467. this._halfpitch = this._pitch * 0.5;
  57468. this._halfyaw = this._yaw * 0.5;
  57469. this._sinRoll = Math.sin(this._halfroll);
  57470. this._cosRoll = Math.cos(this._halfroll);
  57471. this._sinPitch = Math.sin(this._halfpitch);
  57472. this._cosPitch = Math.cos(this._halfpitch);
  57473. this._sinYaw = Math.sin(this._halfyaw);
  57474. this._cosYaw = Math.cos(this._halfyaw);
  57475. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  57476. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  57477. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  57478. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  57479. };
  57480. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  57481. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  57482. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  57483. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  57484. this._rotMatrix.m[3] = 0;
  57485. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  57486. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  57487. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  57488. this._rotMatrix.m[7] = 0;
  57489. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  57490. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  57491. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  57492. this._rotMatrix.m[11] = 0;
  57493. this._rotMatrix.m[12] = 0;
  57494. this._rotMatrix.m[13] = 0;
  57495. this._rotMatrix.m[14] = 0;
  57496. this._rotMatrix.m[15] = 1.0;
  57497. };
  57498. /**
  57499. * Disposes the SPS
  57500. */
  57501. SolidParticleSystem.prototype.dispose = function () {
  57502. this.mesh.dispose();
  57503. this.vars = null;
  57504. // drop references to internal big arrays for the GC
  57505. this._positions = null;
  57506. this._indices = null;
  57507. this._normals = null;
  57508. this._uvs = null;
  57509. this._colors = null;
  57510. this._positions32 = null;
  57511. this._normals32 = null;
  57512. this._fixedNormal32 = null;
  57513. this._uvs32 = null;
  57514. this._colors32 = null;
  57515. this.pickedParticles = null;
  57516. };
  57517. /**
  57518. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  57519. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57520. */
  57521. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  57522. if (!this._isVisibilityBoxLocked) {
  57523. this.mesh.refreshBoundingInfo();
  57524. }
  57525. };
  57526. /**
  57527. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  57528. * @param size the size (float) of the visibility box
  57529. * note : this doesn't lock the SPS mesh bounding box.
  57530. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57531. */
  57532. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  57533. var vis = size / 2;
  57534. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  57535. };
  57536. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  57537. // getter and setter
  57538. get: function () {
  57539. return this._alwaysVisible;
  57540. },
  57541. /**
  57542. * Sets the SPS as always visible or not
  57543. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57544. */
  57545. set: function (val) {
  57546. this._alwaysVisible = val;
  57547. this.mesh.alwaysSelectAsActiveMesh = val;
  57548. },
  57549. enumerable: true,
  57550. configurable: true
  57551. });
  57552. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  57553. get: function () {
  57554. return this._isVisibilityBoxLocked;
  57555. },
  57556. /**
  57557. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  57558. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  57559. */
  57560. set: function (val) {
  57561. this._isVisibilityBoxLocked = val;
  57562. this.mesh.getBoundingInfo().isLocked = val;
  57563. },
  57564. enumerable: true,
  57565. configurable: true
  57566. });
  57567. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  57568. // getters
  57569. get: function () {
  57570. return this._computeParticleRotation;
  57571. },
  57572. // Optimizer setters
  57573. /**
  57574. * Tells to `setParticles()` to compute the particle rotations or not.
  57575. * Default value : true. The SPS is faster when it's set to false.
  57576. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  57577. */
  57578. set: function (val) {
  57579. this._computeParticleRotation = val;
  57580. },
  57581. enumerable: true,
  57582. configurable: true
  57583. });
  57584. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  57585. get: function () {
  57586. return this._computeParticleColor;
  57587. },
  57588. /**
  57589. * Tells to `setParticles()` to compute the particle colors or not.
  57590. * Default value : true. The SPS is faster when it's set to false.
  57591. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  57592. */
  57593. set: function (val) {
  57594. this._computeParticleColor = val;
  57595. },
  57596. enumerable: true,
  57597. configurable: true
  57598. });
  57599. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  57600. get: function () {
  57601. return this._computeParticleTexture;
  57602. },
  57603. /**
  57604. * Tells to `setParticles()` to compute the particle textures or not.
  57605. * Default value : true. The SPS is faster when it's set to false.
  57606. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  57607. */
  57608. set: function (val) {
  57609. this._computeParticleTexture = val;
  57610. },
  57611. enumerable: true,
  57612. configurable: true
  57613. });
  57614. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  57615. get: function () {
  57616. return this._computeParticleVertex;
  57617. },
  57618. /**
  57619. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  57620. * Default value : false. The SPS is faster when it's set to false.
  57621. * Note : the particle custom vertex positions aren't stored values.
  57622. */
  57623. set: function (val) {
  57624. this._computeParticleVertex = val;
  57625. },
  57626. enumerable: true,
  57627. configurable: true
  57628. });
  57629. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  57630. get: function () {
  57631. return this._computeBoundingBox;
  57632. },
  57633. /**
  57634. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  57635. */
  57636. set: function (val) {
  57637. this._computeBoundingBox = val;
  57638. },
  57639. enumerable: true,
  57640. configurable: true
  57641. });
  57642. // =======================================================================
  57643. // Particle behavior logic
  57644. // these following methods may be overwritten by the user to fit his needs
  57645. /**
  57646. * This function does nothing. It may be overwritten to set all the particle first values.
  57647. * The SPS doesn't call this function, you may have to call it by your own.
  57648. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57649. */
  57650. SolidParticleSystem.prototype.initParticles = function () {
  57651. };
  57652. /**
  57653. * This function does nothing. It may be overwritten to recycle a particle.
  57654. * The SPS doesn't call this function, you may have to call it by your own.
  57655. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57656. */
  57657. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  57658. return particle;
  57659. };
  57660. /**
  57661. * Updates a particle : this function should be overwritten by the user.
  57662. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  57663. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  57664. * ex : just set a particle position or velocity and recycle conditions
  57665. */
  57666. SolidParticleSystem.prototype.updateParticle = function (particle) {
  57667. return particle;
  57668. };
  57669. /**
  57670. * Updates a vertex of a particle : it can be overwritten by the user.
  57671. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  57672. * @param particle the current particle
  57673. * @param vertex the current index of the current particle
  57674. * @param pt the index of the current vertex in the particle shape
  57675. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  57676. * ex : just set a vertex particle position
  57677. */
  57678. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  57679. return vertex;
  57680. };
  57681. /**
  57682. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  57683. * This does nothing and may be overwritten by the user.
  57684. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57685. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57686. * @param update the boolean update value actually passed to setParticles()
  57687. */
  57688. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  57689. };
  57690. /**
  57691. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  57692. * This will be passed three parameters.
  57693. * This does nothing and may be overwritten by the user.
  57694. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57695. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  57696. * @param update the boolean update value actually passed to setParticles()
  57697. */
  57698. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  57699. };
  57700. return SolidParticleSystem;
  57701. }());
  57702. BABYLON.SolidParticleSystem = SolidParticleSystem;
  57703. })(BABYLON || (BABYLON = {}));
  57704. var BABYLON;
  57705. (function (BABYLON) {
  57706. var Internals;
  57707. (function (Internals) {
  57708. var FileFaceOrientation = (function () {
  57709. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  57710. this.name = name;
  57711. this.worldAxisForNormal = worldAxisForNormal;
  57712. this.worldAxisForFileX = worldAxisForFileX;
  57713. this.worldAxisForFileY = worldAxisForFileY;
  57714. }
  57715. return FileFaceOrientation;
  57716. }());
  57717. ;
  57718. /**
  57719. * Helper class dealing with the extraction of spherical polynomial dataArray
  57720. * from a cube map.
  57721. */
  57722. var CubeMapToSphericalPolynomialTools = (function () {
  57723. function CubeMapToSphericalPolynomialTools() {
  57724. }
  57725. /**
  57726. * Converts a cubemap to the according Spherical Polynomial data.
  57727. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57728. *
  57729. * @param cubeInfo The Cube map to extract the information from.
  57730. * @return The Spherical Polynomial data.
  57731. */
  57732. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  57733. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  57734. var totalSolidAngle = 0.0;
  57735. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  57736. var du = 2.0 / cubeInfo.size;
  57737. var dv = du;
  57738. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  57739. var minUV = du * 0.5 - 1.0;
  57740. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57741. var fileFace = this.FileFaces[faceIndex];
  57742. var dataArray = cubeInfo[fileFace.name];
  57743. var v = minUV;
  57744. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  57745. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  57746. // Because SP is still linear, so summation is fine in that basis.
  57747. for (var y = 0; y < cubeInfo.size; y++) {
  57748. var u = minUV;
  57749. for (var x = 0; x < cubeInfo.size; x++) {
  57750. // World direction (not normalised)
  57751. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  57752. worldDirection.normalize();
  57753. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  57754. if (1) {
  57755. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  57756. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  57757. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  57758. var color = new BABYLON.Color3(r, g, b);
  57759. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57760. }
  57761. else {
  57762. if (faceIndex == 0) {
  57763. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57764. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57765. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57766. }
  57767. else if (faceIndex == 1) {
  57768. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57769. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57770. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57771. }
  57772. else if (faceIndex == 2) {
  57773. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57774. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57775. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57776. }
  57777. else if (faceIndex == 3) {
  57778. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57779. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57780. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  57781. }
  57782. else if (faceIndex == 4) {
  57783. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  57784. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  57785. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57786. }
  57787. else if (faceIndex == 5) {
  57788. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  57789. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  57790. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  57791. }
  57792. 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]);
  57793. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57794. }
  57795. totalSolidAngle += deltaSolidAngle;
  57796. u += du;
  57797. }
  57798. v += dv;
  57799. }
  57800. }
  57801. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  57802. var correction = correctSolidAngle / totalSolidAngle;
  57803. sphericalHarmonics.scale(correction);
  57804. // Additionally scale by pi -- audit needed
  57805. sphericalHarmonics.scale(1.0 / Math.PI);
  57806. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  57807. };
  57808. CubeMapToSphericalPolynomialTools.FileFaces = [
  57809. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  57810. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  57811. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  57812. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  57813. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  57814. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  57815. ];
  57816. return CubeMapToSphericalPolynomialTools;
  57817. }());
  57818. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  57819. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57820. })(BABYLON || (BABYLON = {}));
  57821. var BABYLON;
  57822. (function (BABYLON) {
  57823. var Internals;
  57824. (function (Internals) {
  57825. /**
  57826. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  57827. */
  57828. var PanoramaToCubeMapTools = (function () {
  57829. function PanoramaToCubeMapTools() {
  57830. }
  57831. /**
  57832. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  57833. *
  57834. * @param float32Array The source data.
  57835. * @param inputWidth The width of the input panorama.
  57836. * @param inputhHeight The height of the input panorama.
  57837. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  57838. * @return The cubemap data
  57839. */
  57840. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  57841. if (!float32Array) {
  57842. throw "ConvertPanoramaToCubemap: input cannot be null";
  57843. }
  57844. if (float32Array.length != inputWidth * inputHeight * 3) {
  57845. throw "ConvertPanoramaToCubemap: input size is wrong";
  57846. }
  57847. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  57848. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  57849. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  57850. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  57851. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  57852. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  57853. return {
  57854. front: textureFront,
  57855. back: textureBack,
  57856. left: textureLeft,
  57857. right: textureRight,
  57858. up: textureUp,
  57859. down: textureDown,
  57860. size: size
  57861. };
  57862. };
  57863. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  57864. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  57865. var textureArray = new Float32Array(buffer);
  57866. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  57867. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  57868. var dy = 1 / texSize;
  57869. var fy = 0;
  57870. for (var y = 0; y < texSize; y++) {
  57871. var xv1 = faceData[0];
  57872. var xv2 = faceData[2];
  57873. for (var x = 0; x < texSize; x++) {
  57874. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  57875. v.normalize();
  57876. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  57877. // 3 channels per pixels
  57878. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  57879. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  57880. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  57881. xv1 = xv1.add(rotDX1);
  57882. xv2 = xv2.add(rotDX2);
  57883. }
  57884. fy += dy;
  57885. }
  57886. return textureArray;
  57887. };
  57888. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  57889. var theta = Math.atan2(vDir.z, vDir.x);
  57890. var phi = Math.acos(vDir.y);
  57891. while (theta < -Math.PI)
  57892. theta += 2 * Math.PI;
  57893. while (theta > Math.PI)
  57894. theta -= 2 * Math.PI;
  57895. var dx = theta / Math.PI;
  57896. var dy = phi / Math.PI;
  57897. // recenter.
  57898. dx = dx * 0.5 + 0.5;
  57899. var px = Math.round(dx * inputWidth);
  57900. if (px < 0)
  57901. px = 0;
  57902. else if (px >= inputWidth)
  57903. px = inputWidth - 1;
  57904. var py = Math.round(dy * inputHeight);
  57905. if (py < 0)
  57906. py = 0;
  57907. else if (py >= inputHeight)
  57908. py = inputHeight - 1;
  57909. var inputY = (inputHeight - py - 1);
  57910. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  57911. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  57912. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  57913. return {
  57914. r: r,
  57915. g: g,
  57916. b: b
  57917. };
  57918. };
  57919. PanoramaToCubeMapTools.FACE_FRONT = [
  57920. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57921. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57922. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57923. new BABYLON.Vector3(1.0, 1.0, -1.0)
  57924. ];
  57925. PanoramaToCubeMapTools.FACE_BACK = [
  57926. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57927. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57928. new BABYLON.Vector3(1.0, 1.0, 1.0),
  57929. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  57930. ];
  57931. PanoramaToCubeMapTools.FACE_RIGHT = [
  57932. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57933. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57934. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57935. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57936. ];
  57937. PanoramaToCubeMapTools.FACE_LEFT = [
  57938. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57939. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57940. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57941. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  57942. ];
  57943. PanoramaToCubeMapTools.FACE_DOWN = [
  57944. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57945. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57946. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57947. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57948. ];
  57949. PanoramaToCubeMapTools.FACE_UP = [
  57950. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57951. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57952. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57953. new BABYLON.Vector3(1.0, -1.0, -1.0)
  57954. ];
  57955. return PanoramaToCubeMapTools;
  57956. }());
  57957. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  57958. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57959. })(BABYLON || (BABYLON = {}));
  57960. var BABYLON;
  57961. (function (BABYLON) {
  57962. var Internals;
  57963. (function (Internals) {
  57964. ;
  57965. /**
  57966. * This groups tools to convert HDR texture to native colors array.
  57967. */
  57968. var HDRTools = (function () {
  57969. function HDRTools() {
  57970. }
  57971. HDRTools.Ldexp = function (mantissa, exponent) {
  57972. if (exponent > 1023) {
  57973. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  57974. }
  57975. if (exponent < -1074) {
  57976. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  57977. }
  57978. return mantissa * Math.pow(2, exponent);
  57979. };
  57980. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  57981. if (exponent > 0) {
  57982. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  57983. float32array[index + 0] = red * exponent;
  57984. float32array[index + 1] = green * exponent;
  57985. float32array[index + 2] = blue * exponent;
  57986. }
  57987. else {
  57988. float32array[index + 0] = 0;
  57989. float32array[index + 1] = 0;
  57990. float32array[index + 2] = 0;
  57991. }
  57992. };
  57993. HDRTools.readStringLine = function (uint8array, startIndex) {
  57994. var line = "";
  57995. var character = "";
  57996. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  57997. character = String.fromCharCode(uint8array[i]);
  57998. if (character == "\n") {
  57999. break;
  58000. }
  58001. line += character;
  58002. }
  58003. return line;
  58004. };
  58005. /**
  58006. * Reads header information from an RGBE texture stored in a native array.
  58007. * More information on this format are available here:
  58008. * https://en.wikipedia.org/wiki/RGBE_image_format
  58009. *
  58010. * @param uint8array The binary file stored in native array.
  58011. * @return The header information.
  58012. */
  58013. HDRTools.RGBE_ReadHeader = function (uint8array) {
  58014. var height = 0;
  58015. var width = 0;
  58016. var line = this.readStringLine(uint8array, 0);
  58017. if (line[0] != '#' || line[1] != '?') {
  58018. throw "Bad HDR Format.";
  58019. }
  58020. var endOfHeader = false;
  58021. var findFormat = false;
  58022. var lineIndex = 0;
  58023. do {
  58024. lineIndex += (line.length + 1);
  58025. line = this.readStringLine(uint8array, lineIndex);
  58026. if (line == "FORMAT=32-bit_rle_rgbe") {
  58027. findFormat = true;
  58028. }
  58029. else if (line.length == 0) {
  58030. endOfHeader = true;
  58031. }
  58032. } while (!endOfHeader);
  58033. if (!findFormat) {
  58034. throw "HDR Bad header format, unsupported FORMAT";
  58035. }
  58036. lineIndex += (line.length + 1);
  58037. line = this.readStringLine(uint8array, lineIndex);
  58038. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  58039. var match = sizeRegexp.exec(line);
  58040. // TODO. Support +Y and -X if needed.
  58041. if (match.length < 3) {
  58042. throw "HDR Bad header format, no size";
  58043. }
  58044. width = parseInt(match[2]);
  58045. height = parseInt(match[1]);
  58046. if (width < 8 || width > 0x7fff) {
  58047. throw "HDR Bad header format, unsupported size";
  58048. }
  58049. lineIndex += (line.length + 1);
  58050. return {
  58051. height: height,
  58052. width: width,
  58053. dataPosition: lineIndex
  58054. };
  58055. };
  58056. /**
  58057. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  58058. * This RGBE texture needs to store the information as a panorama.
  58059. *
  58060. * More information on this format are available here:
  58061. * https://en.wikipedia.org/wiki/RGBE_image_format
  58062. *
  58063. * @param buffer The binary file stored in an array buffer.
  58064. * @param size The expected size of the extracted cubemap.
  58065. * @return The Cube Map information.
  58066. */
  58067. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  58068. var uint8array = new Uint8Array(buffer);
  58069. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  58070. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58071. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  58072. return cubeMapData;
  58073. };
  58074. /**
  58075. * Returns the pixels data extracted from an RGBE texture.
  58076. * This pixels will be stored left to right up to down in the R G B order in one array.
  58077. *
  58078. * More information on this format are available here:
  58079. * https://en.wikipedia.org/wiki/RGBE_image_format
  58080. *
  58081. * @param uint8array The binary file stored in an array buffer.
  58082. * @param hdrInfo The header information of the file.
  58083. * @return The pixels data in RGB right to left up to down order.
  58084. */
  58085. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  58086. // Keep for multi format supports.
  58087. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  58088. };
  58089. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  58090. var num_scanlines = hdrInfo.height;
  58091. var scanline_width = hdrInfo.width;
  58092. var a, b, c, d, count;
  58093. var dataIndex = hdrInfo.dataPosition;
  58094. var index = 0, endIndex = 0, i = 0;
  58095. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  58096. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  58097. // 3 channels of 4 bytes per pixel in float.
  58098. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  58099. var resultArray = new Float32Array(resultBuffer);
  58100. // read in each successive scanline
  58101. while (num_scanlines > 0) {
  58102. a = uint8array[dataIndex++];
  58103. b = uint8array[dataIndex++];
  58104. c = uint8array[dataIndex++];
  58105. d = uint8array[dataIndex++];
  58106. if (a != 2 || b != 2 || (c & 0x80)) {
  58107. // this file is not run length encoded
  58108. throw "HDR Bad header format, not RLE";
  58109. }
  58110. if (((c << 8) | d) != scanline_width) {
  58111. throw "HDR Bad header format, wrong scan line width";
  58112. }
  58113. index = 0;
  58114. // read each of the four channels for the scanline into the buffer
  58115. for (i = 0; i < 4; i++) {
  58116. endIndex = (i + 1) * scanline_width;
  58117. while (index < endIndex) {
  58118. a = uint8array[dataIndex++];
  58119. b = uint8array[dataIndex++];
  58120. if (a > 128) {
  58121. // a run of the same value
  58122. count = a - 128;
  58123. if ((count == 0) || (count > endIndex - index)) {
  58124. throw "HDR Bad Format, bad scanline data (run)";
  58125. }
  58126. while (count-- > 0) {
  58127. scanLineArray[index++] = b;
  58128. }
  58129. }
  58130. else {
  58131. // a non-run
  58132. count = a;
  58133. if ((count == 0) || (count > endIndex - index)) {
  58134. throw "HDR Bad Format, bad scanline data (non-run)";
  58135. }
  58136. scanLineArray[index++] = b;
  58137. if (--count > 0) {
  58138. for (var j = 0; j < count; j++) {
  58139. scanLineArray[index++] = uint8array[dataIndex++];
  58140. }
  58141. }
  58142. }
  58143. }
  58144. }
  58145. // now convert data from buffer into floats
  58146. for (i = 0; i < scanline_width; i++) {
  58147. a = scanLineArray[i];
  58148. b = scanLineArray[i + scanline_width];
  58149. c = scanLineArray[i + 2 * scanline_width];
  58150. d = scanLineArray[i + 3 * scanline_width];
  58151. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  58152. }
  58153. num_scanlines--;
  58154. }
  58155. return resultArray;
  58156. };
  58157. return HDRTools;
  58158. }());
  58159. Internals.HDRTools = HDRTools;
  58160. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  58161. })(BABYLON || (BABYLON = {}));
  58162. //_______________________________________________________________
  58163. // Extracted from CubeMapGen:
  58164. // https://code.google.com/archive/p/cubemapgen/
  58165. //
  58166. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  58167. //_______________________________________________________________
  58168. var BABYLON;
  58169. (function (BABYLON) {
  58170. var Internals;
  58171. (function (Internals) {
  58172. /**
  58173. * The bounding box information used during the conversion process.
  58174. */
  58175. var CMGBoundinBox = (function () {
  58176. function CMGBoundinBox() {
  58177. this.min = new BABYLON.Vector3(0, 0, 0);
  58178. this.max = new BABYLON.Vector3(0, 0, 0);
  58179. this.clear();
  58180. }
  58181. CMGBoundinBox.prototype.clear = function () {
  58182. this.min.x = CMGBoundinBox.MAX;
  58183. this.min.y = CMGBoundinBox.MAX;
  58184. this.min.z = CMGBoundinBox.MAX;
  58185. this.max.x = CMGBoundinBox.MIN;
  58186. this.max.y = CMGBoundinBox.MIN;
  58187. this.max.z = CMGBoundinBox.MIN;
  58188. };
  58189. CMGBoundinBox.prototype.augment = function (x, y, z) {
  58190. this.min.x = Math.min(this.min.x, x);
  58191. this.min.y = Math.min(this.min.y, y);
  58192. this.min.z = Math.min(this.min.z, z);
  58193. this.max.x = Math.max(this.max.x, x);
  58194. this.max.y = Math.max(this.max.y, y);
  58195. this.max.z = Math.max(this.max.z, z);
  58196. };
  58197. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  58198. this.min.x = Math.max(this.min.x, x);
  58199. this.min.y = Math.max(this.min.y, y);
  58200. this.min.z = Math.max(this.min.z, z);
  58201. };
  58202. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  58203. this.max.x = Math.min(this.max.x, x);
  58204. this.max.y = Math.min(this.max.y, y);
  58205. this.max.z = Math.min(this.max.z, z);
  58206. };
  58207. CMGBoundinBox.prototype.empty = function () {
  58208. if ((this.min.x > this.max.y) ||
  58209. (this.min.y > this.max.y) ||
  58210. (this.min.z > this.max.y)) {
  58211. return true;
  58212. }
  58213. else {
  58214. return false;
  58215. }
  58216. };
  58217. CMGBoundinBox.MAX = Number.MAX_VALUE;
  58218. CMGBoundinBox.MIN = Number.MIN_VALUE;
  58219. return CMGBoundinBox;
  58220. }());
  58221. /**
  58222. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  58223. * required by the glossinees of a material.
  58224. *
  58225. * This only supports the cosine drop power as well as Warp fixup generation method.
  58226. *
  58227. * This is using the process from CubeMapGen described here:
  58228. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  58229. */
  58230. var PMREMGenerator = (function () {
  58231. /**
  58232. * Constructor of the generator.
  58233. *
  58234. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  58235. * @param inputSize The size of the cubemap faces
  58236. * @param outputSize The size of the output cubemap faces
  58237. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  58238. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  58239. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  58240. * @param specularPower The max specular level of the desired cubemap
  58241. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  58242. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  58243. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  58244. */
  58245. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  58246. this.input = input;
  58247. this.inputSize = inputSize;
  58248. this.outputSize = outputSize;
  58249. this.maxNumMipLevels = maxNumMipLevels;
  58250. this.numChannels = numChannels;
  58251. this.isFloat = isFloat;
  58252. this.specularPower = specularPower;
  58253. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  58254. this.excludeBase = excludeBase;
  58255. this.fixup = fixup;
  58256. this._outputSurface = [];
  58257. this._numMipLevels = 0;
  58258. }
  58259. /**
  58260. * Launches the filter process and return the result.
  58261. *
  58262. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  58263. */
  58264. PMREMGenerator.prototype.filterCubeMap = function () {
  58265. // Init cubemap processor
  58266. this.init();
  58267. // Filters the cubemap
  58268. this.filterCubeMapMipChain();
  58269. // Returns the filtered mips.
  58270. return this._outputSurface;
  58271. };
  58272. PMREMGenerator.prototype.init = function () {
  58273. var i;
  58274. var j;
  58275. var mipLevelSize;
  58276. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  58277. if (this.maxNumMipLevels == 0) {
  58278. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  58279. }
  58280. //first miplevel size
  58281. mipLevelSize = this.outputSize;
  58282. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  58283. for (j = 0; j < this.maxNumMipLevels; j++) {
  58284. this._outputSurface.length++;
  58285. this._outputSurface[j] = [];
  58286. //Iterate over faces for output images
  58287. for (i = 0; i < 6; i++) {
  58288. this._outputSurface[j].length++;
  58289. // Initializes a new array for the output.
  58290. if (this.isFloat) {
  58291. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  58292. }
  58293. else {
  58294. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  58295. }
  58296. }
  58297. //next mip level is half size
  58298. mipLevelSize >>= 1;
  58299. this._numMipLevels++;
  58300. //terminate if mip chain becomes too small
  58301. if (mipLevelSize == 0) {
  58302. this.maxNumMipLevels = j;
  58303. return;
  58304. }
  58305. }
  58306. };
  58307. //--------------------------------------------------------------------------------------
  58308. //Cube map filtering and mip chain generation.
  58309. // the cube map filtereing is specified using a number of parameters:
  58310. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  58311. // indicates the region of the hemisphere to filter over for each tap.
  58312. //
  58313. // Note that the top mip level is also a filtered version of the original input images
  58314. // as well in order to create mip chains for diffuse environment illumination.
  58315. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  58316. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  58317. //
  58318. // Then the mip angle used to genreate the next level of the mip chain from the first level
  58319. // is a_InitialMipAngle
  58320. //
  58321. // The angle for the subsequent levels of the mip chain are specified by their parents
  58322. // filtering angle and a per-level scale and bias
  58323. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  58324. //
  58325. //--------------------------------------------------------------------------------------
  58326. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  58327. // First, take count of the lighting model to modify SpecularPower
  58328. // 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;
  58329. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  58330. //Cone angle start (for generating subsequent mip levels)
  58331. var currentSpecularPower = this.specularPower;
  58332. //Build filter lookup tables based on the source miplevel size
  58333. this.precomputeFilterLookupTables(this.inputSize);
  58334. // Note that we need to filter the first level before generating mipmap
  58335. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  58336. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  58337. // TODO : Write a function to copy and scale the base mipmap in output
  58338. // I am just lazy here and just put a high specular power value, and do some if.
  58339. if (this.excludeBase && (levelIndex == 0)) {
  58340. // 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).
  58341. currentSpecularPower = 100000.0;
  58342. }
  58343. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  58344. var srcCubeImage = this.input;
  58345. var dstCubeImage = this._outputSurface[levelIndex];
  58346. var dstSize = this.outputSize >> levelIndex;
  58347. // Compute required angle.
  58348. var angle = this.getBaseFilterAngle(currentSpecularPower);
  58349. // filter cube surfaces
  58350. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  58351. // fix seams
  58352. if (this.fixup) {
  58353. this.fixupCubeEdges(dstCubeImage, dstSize);
  58354. }
  58355. // Decrease the specular power to generate the mipmap chain
  58356. // TODO : Use another method for Exclude (see first comment at start of the function
  58357. if (this.excludeBase && (levelIndex == 0)) {
  58358. currentSpecularPower = this.specularPower;
  58359. }
  58360. currentSpecularPower *= this.cosinePowerDropPerMip;
  58361. }
  58362. };
  58363. //--------------------------------------------------------------------------------------
  58364. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  58365. // It allow to optimize the texel to access base on the specular power.
  58366. //--------------------------------------------------------------------------------------
  58367. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  58368. // We want to find the alpha such that:
  58369. // cos(alpha)^cosinePower = epsilon
  58370. // That's: acos(epsilon^(1/cosinePower))
  58371. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  58372. var angle = 180.0;
  58373. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  58374. angle *= 180.0 / Math.PI; // Convert to degree
  58375. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  58376. return angle;
  58377. };
  58378. //--------------------------------------------------------------------------------------
  58379. //Builds the following lookup tables prior to filtering:
  58380. // -normalizer cube map
  58381. // -tap weight lookup table
  58382. //
  58383. //--------------------------------------------------------------------------------------
  58384. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  58385. var srcTexelAngle;
  58386. var iCubeFace;
  58387. //clear pre-existing normalizer cube map
  58388. this._normCubeMap = [];
  58389. //Normalized vectors per cubeface and per-texel solid angle
  58390. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  58391. };
  58392. //--------------------------------------------------------------------------------------
  58393. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  58394. //
  58395. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  58396. //
  58397. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  58398. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  58399. // below
  58400. //--------------------------------------------------------------------------------------
  58401. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  58402. var iCubeFace;
  58403. var u;
  58404. var v;
  58405. //iterate over cube faces
  58406. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58407. //First three channels for norm cube, and last channel for solid angle
  58408. this._normCubeMap.push(new Float32Array(size * size * 4));
  58409. //fast texture walk, build normalizer cube map
  58410. var facesData = this.input[iCubeFace];
  58411. for (v = 0; v < size; v++) {
  58412. for (u = 0; u < size; u++) {
  58413. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  58414. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  58415. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  58416. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  58417. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  58418. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  58419. }
  58420. }
  58421. }
  58422. };
  58423. //--------------------------------------------------------------------------------------
  58424. // Convert cubemap face texel coordinates and face idx to 3D vector
  58425. // note the U and V coords are integer coords and range from 0 to size-1
  58426. // this routine can be used to generate a normalizer cube map
  58427. //--------------------------------------------------------------------------------------
  58428. // SL BEGIN
  58429. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  58430. var nvcU;
  58431. var nvcV;
  58432. var tempVec;
  58433. // Change from original AMD code
  58434. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  58435. // + 0.5f is for texel center addressing
  58436. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  58437. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  58438. // warp fixup
  58439. if (fixup && size > 1) {
  58440. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  58441. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  58442. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  58443. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  58444. }
  58445. // Get current vector
  58446. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  58447. // U contribution
  58448. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  58449. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  58450. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  58451. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  58452. // V contribution and Sum
  58453. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  58454. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  58455. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  58456. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  58457. //add face axis
  58458. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  58459. PMREMGenerator._vectorTemp.x += faceAxis[0];
  58460. PMREMGenerator._vectorTemp.y += faceAxis[1];
  58461. PMREMGenerator._vectorTemp.z += faceAxis[2];
  58462. //normalize vector
  58463. PMREMGenerator._vectorTemp.normalize();
  58464. return PMREMGenerator._vectorTemp;
  58465. };
  58466. //--------------------------------------------------------------------------------------
  58467. // Convert 3D vector to cubemap face texel coordinates and face idx
  58468. // note the U and V coords are integer coords and range from 0 to size-1
  58469. // this routine can be used to generate a normalizer cube map
  58470. //
  58471. // returns face IDX and texel coords
  58472. //--------------------------------------------------------------------------------------
  58473. // SL BEGIN
  58474. /*
  58475. Mapping Texture Coordinates to Cube Map Faces
  58476. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  58477. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  58478. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  58479. map arrangement in Pixar's RenderMan package.
  58480. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  58481. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  58482. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  58483. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  58484. the major axis direction). The target column in the table below explains how the major axis direction
  58485. maps to the 2D image of a particular cube map target.
  58486. major axis
  58487. direction target sc tc ma
  58488. ---------- --------------------------------- --- --- ---
  58489. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  58490. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  58491. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  58492. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  58493. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  58494. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  58495. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  58496. an updated (s,t) is calculated as follows
  58497. s = ( sc/|ma| + 1 ) / 2
  58498. t = ( tc/|ma| + 1 ) / 2
  58499. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  58500. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  58501. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  58502. */
  58503. // Note this method return U and V in range from 0 to size-1
  58504. // SL END
  58505. // Store the information in vector3 for convenience (faceindex, u, v)
  58506. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  58507. var maxCoord;
  58508. var faceIdx;
  58509. //absolute value 3
  58510. var absX = Math.abs(x);
  58511. var absY = Math.abs(y);
  58512. var absZ = Math.abs(z);
  58513. if (absX >= absY && absX >= absZ) {
  58514. maxCoord = absX;
  58515. if (x >= 0) {
  58516. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  58517. }
  58518. else {
  58519. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  58520. }
  58521. }
  58522. else if (absY >= absX && absY >= absZ) {
  58523. maxCoord = absY;
  58524. if (y >= 0) {
  58525. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  58526. }
  58527. else {
  58528. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  58529. }
  58530. }
  58531. else {
  58532. maxCoord = absZ;
  58533. if (z >= 0) {
  58534. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  58535. }
  58536. else {
  58537. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  58538. }
  58539. }
  58540. //divide through by max coord so face vector lies on cube face
  58541. var scale = 1 / maxCoord;
  58542. x *= scale;
  58543. y *= scale;
  58544. z *= scale;
  58545. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  58546. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  58547. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  58548. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  58549. // Modify original AMD code to return value from 0 to Size - 1
  58550. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  58551. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  58552. PMREMGenerator._vectorTemp.x = faceIdx;
  58553. PMREMGenerator._vectorTemp.y = u;
  58554. PMREMGenerator._vectorTemp.z = v;
  58555. return PMREMGenerator._vectorTemp;
  58556. };
  58557. //--------------------------------------------------------------------------------------
  58558. //Original code from Ignacio CastaÒo
  58559. // This formula is from Manne ÷hrstrˆm's thesis.
  58560. // Take two coordiantes in the range [-1, 1] that define a portion of a
  58561. // cube face and return the area of the projection of that portion on the
  58562. // surface of the sphere.
  58563. //--------------------------------------------------------------------------------------
  58564. PMREMGenerator.prototype.areaElement = function (x, y) {
  58565. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  58566. };
  58567. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  58568. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  58569. // (+ 0.5f is for texel center addressing)
  58570. u = (2.0 * (u + 0.5) / size) - 1.0;
  58571. v = (2.0 * (v + 0.5) / size) - 1.0;
  58572. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  58573. var invResolution = 1.0 / size;
  58574. // U and V are the -1..1 texture coordinate on the current face.
  58575. // Get projected area for this texel
  58576. var x0 = u - invResolution;
  58577. var y0 = v - invResolution;
  58578. var x1 = u + invResolution;
  58579. var y1 = v + invResolution;
  58580. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  58581. return solidAngle;
  58582. };
  58583. //--------------------------------------------------------------------------------------
  58584. //The key to the speed of these filtering routines is to quickly define a per-face
  58585. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  58586. // Later these pixels are selectively processed based on their dot products to see if
  58587. // they reside within the filtering cone.
  58588. //
  58589. //This is done by computing the smallest per-texel angle to get a conservative estimate
  58590. // of the number of texels needed to be covered in width and height order to filter the
  58591. // region. the bounding box for the center taps face is defined first, and if the
  58592. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  58593. // defined next
  58594. //--------------------------------------------------------------------------------------
  58595. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  58596. // note that pixels within these regions may be rejected
  58597. // based on the anlge
  58598. var iCubeFace;
  58599. var u;
  58600. var v;
  58601. // bounding box per face to specify region to process
  58602. var filterExtents = [];
  58603. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58604. filterExtents.push(new CMGBoundinBox());
  58605. }
  58606. // min angle a src texel can cover (in degrees)
  58607. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  58608. // angle about center tap to define filter cone
  58609. // filter angle is 1/2 the cone angle
  58610. var filterAngle = filterConeAngle / 2.0;
  58611. //ensure filter angle is larger than a texel
  58612. if (filterAngle < srcTexelAngle) {
  58613. filterAngle = srcTexelAngle;
  58614. }
  58615. //ensure filter cone is always smaller than the hemisphere
  58616. if (filterAngle > 90.0) {
  58617. filterAngle = 90.0;
  58618. }
  58619. // the maximum number of texels in 1D the filter cone angle will cover
  58620. // used to determine bounding box size for filter extents
  58621. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  58622. // ensure conservative region always covers at least one texel
  58623. if (filterSize < 1) {
  58624. filterSize = 1;
  58625. }
  58626. // dotProdThresh threshold based on cone angle to determine whether or not taps
  58627. // reside within the cone angle
  58628. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  58629. // process required faces
  58630. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  58631. //iterate over dst cube map face texel
  58632. for (v = 0; v < dstSize; v++) {
  58633. for (u = 0; u < dstSize; u++) {
  58634. //get center tap direction
  58635. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  58636. //clear old per-face filter extents
  58637. this.clearFilterExtents(filterExtents);
  58638. //define per-face filter extents
  58639. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  58640. //perform filtering of src faces using filter extents
  58641. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  58642. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  58643. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  58644. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  58645. }
  58646. }
  58647. }
  58648. };
  58649. //--------------------------------------------------------------------------------------
  58650. //Clear filter extents for the 6 cube map faces
  58651. //--------------------------------------------------------------------------------------
  58652. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  58653. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  58654. filterExtents[iCubeFaces].clear();
  58655. }
  58656. };
  58657. //--------------------------------------------------------------------------------------
  58658. //Define per-face bounding box filter extents
  58659. //
  58660. // These define conservative texel regions in each of the faces the filter can possibly
  58661. // process. When the pixels in the regions are actually processed, the dot product
  58662. // between the tap vector and the center tap vector is used to determine the weight of
  58663. // the tap and whether or not the tap is within the cone.
  58664. //
  58665. //--------------------------------------------------------------------------------------
  58666. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  58667. //neighboring face and bleed over amount, and width of BBOX for
  58668. // left, right, top, and bottom edges of this face
  58669. var bleedOverAmount = [0, 0, 0, 0];
  58670. var bleedOverBBoxMin = [0, 0, 0, 0];
  58671. var bleedOverBBoxMax = [0, 0, 0, 0];
  58672. var neighborFace;
  58673. var neighborEdge;
  58674. var oppositeFaceIdx;
  58675. //get face idx, and u, v info from center tap dir
  58676. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  58677. var faceIdx = result.x;
  58678. var u = result.y;
  58679. var v = result.z;
  58680. //define bbox size within face
  58681. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  58682. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  58683. filterExtents[faceIdx].clampMin(0, 0, 0);
  58684. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  58685. //u and v extent in face corresponding to center tap
  58686. var minU = filterExtents[faceIdx].min.x;
  58687. var minV = filterExtents[faceIdx].min.y;
  58688. var maxU = filterExtents[faceIdx].max.x;
  58689. var maxV = filterExtents[faceIdx].max.y;
  58690. //bleed over amounts for face across u=0 edge (left)
  58691. bleedOverAmount[0] = (bboxSize - u);
  58692. bleedOverBBoxMin[0] = minV;
  58693. bleedOverBBoxMax[0] = maxV;
  58694. //bleed over amounts for face across u=1 edge (right)
  58695. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  58696. bleedOverBBoxMin[1] = minV;
  58697. bleedOverBBoxMax[1] = maxV;
  58698. //bleed over to face across v=0 edge (up)
  58699. bleedOverAmount[2] = (bboxSize - v);
  58700. bleedOverBBoxMin[2] = minU;
  58701. bleedOverBBoxMax[2] = maxU;
  58702. //bleed over to face across v=1 edge (down)
  58703. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  58704. bleedOverBBoxMin[3] = minU;
  58705. bleedOverBBoxMax[3] = maxU;
  58706. //compute bleed over regions in neighboring faces
  58707. for (var i = 0; i < 4; i++) {
  58708. if (bleedOverAmount[i] > 0) {
  58709. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  58710. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  58711. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  58712. // be flipped: the cases are
  58713. // if a left edge mates with a left or bottom edge on the neighbor
  58714. // if a top edge mates with a top or right edge on the neighbor
  58715. // if a right edge mates with a right or top edge on the neighbor
  58716. // if a bottom edge mates with a bottom or left edge on the neighbor
  58717. //Seeing as the edges are enumerated as follows
  58718. // left =0
  58719. // right =1
  58720. // top =2
  58721. // bottom =3
  58722. //
  58723. // so if the edge enums are the same, or the sum of the enums == 3,
  58724. // the bbox needs to be flipped
  58725. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  58726. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  58727. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  58728. }
  58729. //The way the bounding box is extended onto the neighboring face
  58730. // depends on which edge of neighboring face abuts with this one
  58731. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  58732. case PMREMGenerator.CP_EDGE_LEFT:
  58733. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  58734. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  58735. break;
  58736. case PMREMGenerator.CP_EDGE_RIGHT:
  58737. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  58738. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  58739. break;
  58740. case PMREMGenerator.CP_EDGE_TOP:
  58741. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  58742. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  58743. break;
  58744. case PMREMGenerator.CP_EDGE_BOTTOM:
  58745. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  58746. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  58747. break;
  58748. }
  58749. //clamp filter extents in non-center tap faces to remain within surface
  58750. filterExtents[neighborFace].clampMin(0, 0, 0);
  58751. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  58752. }
  58753. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  58754. // from the center tap face, then process the opposite face entirely for now.
  58755. //Note that the cases in which this happens, what usually happens is that
  58756. // more than one edge bleeds onto the opposite face, and the bounding box
  58757. // encompasses the entire cube map face.
  58758. if (bleedOverAmount[i] > srcSize) {
  58759. //determine opposite face
  58760. switch (faceIdx) {
  58761. case PMREMGenerator.CP_FACE_X_POS:
  58762. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  58763. break;
  58764. case PMREMGenerator.CP_FACE_X_NEG:
  58765. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  58766. break;
  58767. case PMREMGenerator.CP_FACE_Y_POS:
  58768. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  58769. break;
  58770. case PMREMGenerator.CP_FACE_Y_NEG:
  58771. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  58772. break;
  58773. case PMREMGenerator.CP_FACE_Z_POS:
  58774. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  58775. break;
  58776. case PMREMGenerator.CP_FACE_Z_NEG:
  58777. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  58778. break;
  58779. default:
  58780. break;
  58781. }
  58782. //just encompass entire face for now
  58783. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  58784. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  58785. }
  58786. }
  58787. };
  58788. //--------------------------------------------------------------------------------------
  58789. //ProcessFilterExtents
  58790. // Process bounding box in each cube face
  58791. //
  58792. //--------------------------------------------------------------------------------------
  58793. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  58794. //accumulators are 64-bit floats in order to have the precision needed
  58795. // over a summation of a large number of pixels
  58796. var dstAccum = [0, 0, 0, 0];
  58797. var weightAccum = 0;
  58798. var k = 0;
  58799. var nSrcChannels = this.numChannels;
  58800. // norm cube map and srcCubeMap have same face width
  58801. var faceWidth = srcSize;
  58802. //amount to add to pointer to move to next scanline in images
  58803. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  58804. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  58805. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  58806. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  58807. // iterate over cubefaces
  58808. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  58809. //if bbox is non empty
  58810. if (!filterExtents[iFaceIdx].empty()) {
  58811. var uStart = filterExtents[iFaceIdx].min.x;
  58812. var vStart = filterExtents[iFaceIdx].min.y;
  58813. var uEnd = filterExtents[iFaceIdx].max.x;
  58814. var vEnd = filterExtents[iFaceIdx].max.y;
  58815. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  58816. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  58817. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  58818. for (var v = vStart; v <= vEnd; v++) {
  58819. var normCubeRowWalk = 0;
  58820. var srcCubeRowWalk = 0;
  58821. for (var u = uStart; u <= uEnd; u++) {
  58822. //pointer to direction in cube map associated with texel
  58823. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  58824. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  58825. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  58826. //check dot product to see if texel is within cone
  58827. var tapDotProd = texelVectX * centerTapDir.x +
  58828. texelVectY * centerTapDir.y +
  58829. texelVectZ * centerTapDir.z;
  58830. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  58831. //solid angle stored in 4th channel of normalizer/solid angle cube map
  58832. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  58833. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  58834. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  58835. // so just adding one to specularpower do the trick.
  58836. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  58837. //iterate over channels
  58838. for (k = 0; k < nSrcChannels; k++) {
  58839. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  58840. srcCubeRowWalk++;
  58841. }
  58842. weightAccum += weight; //accumulate weight
  58843. }
  58844. else {
  58845. //step across source pixel
  58846. srcCubeRowWalk += nSrcChannels;
  58847. }
  58848. normCubeRowWalk += 4; // 4 channels per norm cube map.
  58849. }
  58850. startIndexNormCubeMap += normCubePitch;
  58851. startIndexSrcCubeMap += srcCubePitch;
  58852. }
  58853. }
  58854. }
  58855. //divide through by weights if weight is non zero
  58856. if (weightAccum != 0.0) {
  58857. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  58858. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  58859. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  58860. if (this.numChannels > 3) {
  58861. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  58862. }
  58863. }
  58864. else {
  58865. // otherwise sample nearest
  58866. // get face idx and u, v texel coordinate in face
  58867. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  58868. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  58869. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  58870. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  58871. if (this.numChannels > 3) {
  58872. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  58873. }
  58874. }
  58875. return PMREMGenerator._vectorTemp;
  58876. };
  58877. //--------------------------------------------------------------------------------------
  58878. // Fixup cube edges
  58879. //
  58880. // average texels on cube map faces across the edges
  58881. // WARP/BENT Method Only.
  58882. //--------------------------------------------------------------------------------------
  58883. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  58884. var k;
  58885. var j;
  58886. var i;
  58887. var iFace;
  58888. var iCorner = 0;
  58889. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  58890. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  58891. // note that if functionality to filter across the three texels for each corner, then
  58892. //indexed by corner and face idx. the array contains the face the start points belongs to.
  58893. var cornerPtr = [
  58894. [[], [], []],
  58895. [[], [], []],
  58896. [[], [], []],
  58897. [[], [], []],
  58898. [[], [], []],
  58899. [[], [], []],
  58900. [[], [], []],
  58901. [[], [], []]
  58902. ];
  58903. //if there is no fixup, or fixup width = 0, do nothing
  58904. if (cubeMapSize < 1) {
  58905. return;
  58906. }
  58907. //special case 1x1 cubemap, average face colors
  58908. if (cubeMapSize == 1) {
  58909. //iterate over channels
  58910. for (k = 0; k < this.numChannels; k++) {
  58911. var accum = 0.0;
  58912. //iterate over faces to accumulate face colors
  58913. for (iFace = 0; iFace < 6; iFace++) {
  58914. accum += cubeMap[iFace][k];
  58915. }
  58916. //compute average over 6 face colors
  58917. accum /= 6.0;
  58918. //iterate over faces to distribute face colors
  58919. for (iFace = 0; iFace < 6; iFace++) {
  58920. cubeMap[iFace][k] = accum;
  58921. }
  58922. }
  58923. return;
  58924. }
  58925. //iterate over faces to collect list of corner texel pointers
  58926. for (iFace = 0; iFace < 6; iFace++) {
  58927. //the 4 corner pointers for this face
  58928. faceCornerStartIndicies[0] = [iFace, 0];
  58929. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  58930. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  58931. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  58932. //iterate over face corners to collect cube corner pointers
  58933. for (iCorner = 0; iCorner < 4; iCorner++) {
  58934. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  58935. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  58936. cornerNumPtrs[corner]++;
  58937. }
  58938. }
  58939. //iterate over corners to average across corner tap values
  58940. for (iCorner = 0; iCorner < 8; iCorner++) {
  58941. for (k = 0; k < this.numChannels; k++) {
  58942. var cornerTapAccum = 0.0;
  58943. //iterate over corner texels and average results
  58944. for (i = 0; i < 3; i++) {
  58945. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  58946. }
  58947. //divide by 3 to compute average of corner tap values
  58948. cornerTapAccum *= (1.0 / 3.0);
  58949. //iterate over corner texels and average results
  58950. for (i = 0; i < 3; i++) {
  58951. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  58952. }
  58953. }
  58954. }
  58955. //iterate over the twelve edges of the cube to average across edges
  58956. for (i = 0; i < 12; i++) {
  58957. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  58958. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  58959. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  58960. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  58961. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  58962. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  58963. var edgeWalk = 0;
  58964. var neighborEdgeWalk = 0;
  58965. //Determine walking pointers based on edge type
  58966. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  58967. switch (edge) {
  58968. case PMREMGenerator.CP_EDGE_LEFT:
  58969. // no change to faceEdgeStartPtr
  58970. edgeWalk = this.numChannels * cubeMapSize;
  58971. break;
  58972. case PMREMGenerator.CP_EDGE_RIGHT:
  58973. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  58974. edgeWalk = this.numChannels * cubeMapSize;
  58975. break;
  58976. case PMREMGenerator.CP_EDGE_TOP:
  58977. // no change to faceEdgeStartPtr
  58978. edgeWalk = this.numChannels;
  58979. break;
  58980. case PMREMGenerator.CP_EDGE_BOTTOM:
  58981. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  58982. edgeWalk = this.numChannels;
  58983. break;
  58984. }
  58985. //For certain types of edge abutments, the neighbor edge walk needs to
  58986. // be flipped: the cases are
  58987. // if a left edge mates with a left or bottom edge on the neighbor
  58988. // if a top edge mates with a top or right edge on the neighbor
  58989. // if a right edge mates with a right or top edge on the neighbor
  58990. // if a bottom edge mates with a bottom or left edge on the neighbor
  58991. //Seeing as the edges are enumerated as follows
  58992. // left =0
  58993. // right =1
  58994. // top =2
  58995. // bottom =3
  58996. //
  58997. //If the edge enums are the same, or the sum of the enums == 3,
  58998. // the neighbor edge walk needs to be flipped
  58999. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  59000. switch (neighborEdge) {
  59001. case PMREMGenerator.CP_EDGE_LEFT:
  59002. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  59003. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  59004. break;
  59005. case PMREMGenerator.CP_EDGE_RIGHT:
  59006. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  59007. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  59008. break;
  59009. case PMREMGenerator.CP_EDGE_TOP:
  59010. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59011. neighborEdgeWalk = -this.numChannels;
  59012. break;
  59013. case PMREMGenerator.CP_EDGE_BOTTOM:
  59014. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  59015. neighborEdgeWalk = -this.numChannels;
  59016. break;
  59017. }
  59018. }
  59019. else {
  59020. //swapped direction neighbor edge walk
  59021. switch (neighborEdge) {
  59022. case PMREMGenerator.CP_EDGE_LEFT:
  59023. //no change to neighborEdgeStartPtr for this case since it points
  59024. // to the upper left corner already
  59025. neighborEdgeWalk = this.numChannels * cubeMapSize;
  59026. break;
  59027. case PMREMGenerator.CP_EDGE_RIGHT:
  59028. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  59029. neighborEdgeWalk = this.numChannels * cubeMapSize;
  59030. break;
  59031. case PMREMGenerator.CP_EDGE_TOP:
  59032. //no change to neighborEdgeStartPtr for this case since it points
  59033. // to the upper left corner already
  59034. neighborEdgeWalk = this.numChannels;
  59035. break;
  59036. case PMREMGenerator.CP_EDGE_BOTTOM:
  59037. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  59038. neighborEdgeWalk = this.numChannels;
  59039. break;
  59040. }
  59041. }
  59042. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  59043. //nearby neighborhood
  59044. //step ahead one texel on edge
  59045. edgeStartIndex += edgeWalk;
  59046. neighborEdgeStartIndex += neighborEdgeWalk;
  59047. // note that this loop does not process the corner texels, since they have already been
  59048. // averaged across faces across earlier
  59049. for (j = 1; j < (cubeMapSize - 1); j++) {
  59050. //for each set of taps along edge, average them
  59051. // and rewrite the results into the edges
  59052. for (k = 0; k < this.numChannels; k++) {
  59053. var edgeTap = cubeMap[face][edgeStartIndex + k];
  59054. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  59055. //compute average of tap intensity values
  59056. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  59057. //propagate average of taps to edge taps
  59058. cubeMap[face][edgeStartIndex + k] = avgTap;
  59059. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  59060. }
  59061. edgeStartIndex += edgeWalk;
  59062. neighborEdgeStartIndex += neighborEdgeWalk;
  59063. }
  59064. }
  59065. };
  59066. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  59067. PMREMGenerator.CP_UDIR = 0;
  59068. PMREMGenerator.CP_VDIR = 1;
  59069. PMREMGenerator.CP_FACEAXIS = 2;
  59070. //used to index cube faces
  59071. PMREMGenerator.CP_FACE_X_POS = 0;
  59072. PMREMGenerator.CP_FACE_X_NEG = 1;
  59073. PMREMGenerator.CP_FACE_Y_POS = 2;
  59074. PMREMGenerator.CP_FACE_Y_NEG = 3;
  59075. PMREMGenerator.CP_FACE_Z_POS = 4;
  59076. PMREMGenerator.CP_FACE_Z_NEG = 5;
  59077. //used to index image edges
  59078. // NOTE.. the actual number corresponding to the edge is important
  59079. // do not change these, or the code will break
  59080. //
  59081. // CP_EDGE_LEFT is u = 0
  59082. // CP_EDGE_RIGHT is u = width-1
  59083. // CP_EDGE_TOP is v = 0
  59084. // CP_EDGE_BOTTOM is v = height-1
  59085. PMREMGenerator.CP_EDGE_LEFT = 0;
  59086. PMREMGenerator.CP_EDGE_RIGHT = 1;
  59087. PMREMGenerator.CP_EDGE_TOP = 2;
  59088. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  59089. //corners of CUBE map (P or N specifys if it corresponds to the
  59090. // positive or negative direction each of X, Y, and Z
  59091. PMREMGenerator.CP_CORNER_NNN = 0;
  59092. PMREMGenerator.CP_CORNER_NNP = 1;
  59093. PMREMGenerator.CP_CORNER_NPN = 2;
  59094. PMREMGenerator.CP_CORNER_NPP = 3;
  59095. PMREMGenerator.CP_CORNER_PNN = 4;
  59096. PMREMGenerator.CP_CORNER_PNP = 5;
  59097. PMREMGenerator.CP_CORNER_PPN = 6;
  59098. PMREMGenerator.CP_CORNER_PPP = 7;
  59099. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  59100. //3x2 matrices that map cube map indexing vectors in 3d
  59101. // (after face selection and divide through by the
  59102. // _ABSOLUTE VALUE_ of the max coord)
  59103. // into NVC space
  59104. //Note this currently assumes the D3D cube face ordering and orientation
  59105. PMREMGenerator._sgFace2DMapping = [
  59106. //XPOS face
  59107. [[0, 0, -1],
  59108. [0, -1, 0],
  59109. [1, 0, 0]],
  59110. //XNEG face
  59111. [[0, 0, 1],
  59112. [0, -1, 0],
  59113. [-1, 0, 0]],
  59114. //YPOS face
  59115. [[1, 0, 0],
  59116. [0, 0, 1],
  59117. [0, 1, 0]],
  59118. //YNEG face
  59119. [[1, 0, 0],
  59120. [0, 0, -1],
  59121. [0, -1, 0]],
  59122. //ZPOS face
  59123. [[1, 0, 0],
  59124. [0, -1, 0],
  59125. [0, 0, 1]],
  59126. //ZNEG face
  59127. [[-1, 0, 0],
  59128. [0, -1, 0],
  59129. [0, 0, -1]],
  59130. ];
  59131. //------------------------------------------------------------------------------
  59132. // D3D cube map face specification
  59133. // mapping from 3D x,y,z cube map lookup coordinates
  59134. // to 2D within face u,v coordinates
  59135. //
  59136. // --------------------> U direction
  59137. // | (within-face texture space)
  59138. // | _____
  59139. // | | |
  59140. // | | +Y |
  59141. // | _____|_____|_____ _____
  59142. // | | | | | |
  59143. // | | -X | +Z | +X | -Z |
  59144. // | |_____|_____|_____|_____|
  59145. // | | |
  59146. // | | -Y |
  59147. // | |_____|
  59148. // |
  59149. // v V direction
  59150. // (within-face texture space)
  59151. //------------------------------------------------------------------------------
  59152. //Information about neighbors and how texture coorrdinates change across faces
  59153. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  59154. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  59155. //Note this currently assumes the D3D cube face ordering and orientation
  59156. PMREMGenerator._sgCubeNgh = [
  59157. //XPOS face
  59158. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59159. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59160. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59161. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  59162. //XNEG face
  59163. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59164. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  59165. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  59166. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  59167. //YPOS face
  59168. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  59169. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  59170. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  59171. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  59172. //YNEG face
  59173. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  59174. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59175. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59176. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  59177. //ZPOS face
  59178. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59179. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  59180. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59181. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  59182. //ZNEG face
  59183. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59184. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59185. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  59186. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  59187. ];
  59188. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  59189. // this table is used to average over the edges.
  59190. PMREMGenerator._sgCubeEdgeList = [
  59191. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  59192. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  59193. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  59194. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59195. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  59196. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  59197. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  59198. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  59199. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  59200. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  59201. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  59202. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  59203. ];
  59204. //Information about which of the 8 cube corners are correspond to the
  59205. // the 4 corners in each cube face
  59206. // the order is upper left, upper right, lower left, lower right
  59207. PMREMGenerator._sgCubeCornerList = [
  59208. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  59209. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  59210. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  59211. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  59212. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  59213. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  59214. ];
  59215. return PMREMGenerator;
  59216. }());
  59217. Internals.PMREMGenerator = PMREMGenerator;
  59218. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  59219. })(BABYLON || (BABYLON = {}));
  59220. var BABYLON;
  59221. (function (BABYLON) {
  59222. /**
  59223. * This represents a texture coming from an HDR input.
  59224. *
  59225. * The only supported format is currently panorama picture stored in RGBE format.
  59226. * Example of such files can be found on HDRLib: http://hdrlib.com/
  59227. */
  59228. var HDRCubeTexture = (function (_super) {
  59229. __extends(HDRCubeTexture, _super);
  59230. /**
  59231. * Instantiates an HDRTexture from the following parameters.
  59232. *
  59233. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  59234. * @param scene The scene the texture will be used in
  59235. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  59236. * @param noMipmap Forces to not generate the mipmap if true
  59237. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  59238. * @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)
  59239. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  59240. */
  59241. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  59242. if (noMipmap === void 0) { noMipmap = false; }
  59243. if (generateHarmonics === void 0) { generateHarmonics = true; }
  59244. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  59245. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  59246. _super.call(this, scene);
  59247. this._useInGammaSpace = false;
  59248. this._generateHarmonics = true;
  59249. this._isBABYLONPreprocessed = false;
  59250. /**
  59251. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  59252. */
  59253. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  59254. /**
  59255. * The spherical polynomial data extracted from the texture.
  59256. */
  59257. this.sphericalPolynomial = null;
  59258. /**
  59259. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  59260. * This is usefull at run time to apply the good shader.
  59261. */
  59262. this.isPMREM = false;
  59263. if (!url) {
  59264. return;
  59265. }
  59266. this.name = url;
  59267. this.url = url;
  59268. this.hasAlpha = false;
  59269. this.isCube = true;
  59270. this._textureMatrix = BABYLON.Matrix.Identity();
  59271. if (size) {
  59272. this._isBABYLONPreprocessed = false;
  59273. this._noMipmap = noMipmap;
  59274. this._size = size;
  59275. this._useInGammaSpace = useInGammaSpace;
  59276. this._usePMREMGenerator = usePMREMGenerator &&
  59277. scene.getEngine().getCaps().textureLOD &&
  59278. this.getScene().getEngine().getCaps().textureFloat &&
  59279. !this._useInGammaSpace;
  59280. }
  59281. else {
  59282. this._isBABYLONPreprocessed = true;
  59283. this._noMipmap = false;
  59284. this._useInGammaSpace = false;
  59285. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  59286. this.getScene().getEngine().getCaps().textureFloat &&
  59287. !this._useInGammaSpace;
  59288. }
  59289. this.isPMREM = this._usePMREMGenerator;
  59290. this._texture = this._getFromCache(url, this._noMipmap);
  59291. if (!this._texture) {
  59292. if (!scene.useDelayedTextureLoading) {
  59293. this.loadTexture();
  59294. }
  59295. else {
  59296. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  59297. }
  59298. }
  59299. }
  59300. /**
  59301. * Occurs when the file is a preprocessed .babylon.hdr file.
  59302. */
  59303. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  59304. var _this = this;
  59305. var mipLevels = 0;
  59306. var floatArrayView = null;
  59307. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  59308. var mips = [];
  59309. var startIndex = 30;
  59310. for (var level = 0; level < mipLevels; level++) {
  59311. mips.push([]);
  59312. // Fill each pixel of the mip level.
  59313. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  59314. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59315. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  59316. mips[level].push(faceData);
  59317. startIndex += faceSize;
  59318. }
  59319. }
  59320. return mips;
  59321. } : null;
  59322. var callback = function (buffer) {
  59323. // Create Native Array Views
  59324. var intArrayView = new Int32Array(buffer);
  59325. floatArrayView = new Float32Array(buffer);
  59326. // Fill header.
  59327. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  59328. _this._size = intArrayView[1]; // CubeMap max mip face size.
  59329. // Update Texture Information.
  59330. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  59331. // Fill polynomial information.
  59332. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  59333. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  59334. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  59335. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  59336. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  59337. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  59338. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  59339. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  59340. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  59341. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  59342. // Fill pixel data.
  59343. mipLevels = intArrayView[29]; // Number of mip levels.
  59344. var startIndex = 30;
  59345. var data = [];
  59346. var faceSize = Math.pow(_this._size, 2) * 3;
  59347. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59348. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  59349. startIndex += faceSize;
  59350. }
  59351. var results = [];
  59352. var byteArray = null;
  59353. // Push each faces.
  59354. for (var k = 0; k < 6; k++) {
  59355. var dataFace = null;
  59356. // If special cases.
  59357. if (!mipmapGenerator) {
  59358. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  59359. dataFace = data[j];
  59360. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59361. // 3 channels of 1 bytes per pixel in bytes.
  59362. var byteBuffer = new ArrayBuffer(faceSize);
  59363. byteArray = new Uint8Array(byteBuffer);
  59364. }
  59365. for (var i = 0; i < _this._size * _this._size; i++) {
  59366. // Put in gamma space if requested.
  59367. if (_this._useInGammaSpace) {
  59368. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59369. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59370. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59371. }
  59372. // Convert to int texture for fallback.
  59373. if (byteArray) {
  59374. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59375. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59376. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59377. // May use luminance instead if the result is not accurate.
  59378. var max = Math.max(Math.max(r, g), b);
  59379. if (max > 255) {
  59380. var scale = 255 / max;
  59381. r *= scale;
  59382. g *= scale;
  59383. b *= scale;
  59384. }
  59385. byteArray[(i * 3) + 0] = r;
  59386. byteArray[(i * 3) + 1] = g;
  59387. byteArray[(i * 3) + 2] = b;
  59388. }
  59389. }
  59390. }
  59391. else {
  59392. dataFace = data[k];
  59393. }
  59394. // Fill the array accordingly.
  59395. if (byteArray) {
  59396. results.push(byteArray);
  59397. }
  59398. else {
  59399. results.push(dataFace);
  59400. }
  59401. }
  59402. return results;
  59403. };
  59404. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
  59405. };
  59406. /**
  59407. * Occurs when the file is raw .hdr file.
  59408. */
  59409. HDRCubeTexture.prototype.loadHDRTexture = function () {
  59410. var _this = this;
  59411. var callback = function (buffer) {
  59412. // Extract the raw linear data.
  59413. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  59414. // Generate harmonics if needed.
  59415. if (_this._generateHarmonics) {
  59416. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  59417. }
  59418. var results = [];
  59419. var byteArray = null;
  59420. // Push each faces.
  59421. for (var j = 0; j < 6; j++) {
  59422. // Create uintarray fallback.
  59423. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  59424. // 3 channels of 1 bytes per pixel in bytes.
  59425. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  59426. byteArray = new Uint8Array(byteBuffer);
  59427. }
  59428. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  59429. // If special cases.
  59430. if (_this._useInGammaSpace || byteArray) {
  59431. for (var i = 0; i < _this._size * _this._size; i++) {
  59432. // Put in gamma space if requested.
  59433. if (_this._useInGammaSpace) {
  59434. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  59435. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  59436. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  59437. }
  59438. // Convert to int texture for fallback.
  59439. if (byteArray) {
  59440. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  59441. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  59442. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  59443. // May use luminance instead if the result is not accurate.
  59444. var max = Math.max(Math.max(r, g), b);
  59445. if (max > 255) {
  59446. var scale = 255 / max;
  59447. r *= scale;
  59448. g *= scale;
  59449. b *= scale;
  59450. }
  59451. byteArray[(i * 3) + 0] = r;
  59452. byteArray[(i * 3) + 1] = g;
  59453. byteArray[(i * 3) + 2] = b;
  59454. }
  59455. }
  59456. }
  59457. if (byteArray) {
  59458. results.push(byteArray);
  59459. }
  59460. else {
  59461. results.push(dataFace);
  59462. }
  59463. }
  59464. return results;
  59465. };
  59466. var mipmapGenerator = null;
  59467. if (!this._noMipmap &&
  59468. this._usePMREMGenerator) {
  59469. mipmapGenerator = function (data) {
  59470. // Custom setup of the generator matching with the PBR shader values.
  59471. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  59472. return generator.filterCubeMap();
  59473. };
  59474. }
  59475. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
  59476. };
  59477. /**
  59478. * Starts the loading process of the texture.
  59479. */
  59480. HDRCubeTexture.prototype.loadTexture = function () {
  59481. if (this._isBABYLONPreprocessed) {
  59482. this.loadBabylonTexture();
  59483. }
  59484. else {
  59485. this.loadHDRTexture();
  59486. }
  59487. };
  59488. HDRCubeTexture.prototype.clone = function () {
  59489. var size = this._isBABYLONPreprocessed ? null : this._size;
  59490. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  59491. // Base texture
  59492. newTexture.level = this.level;
  59493. newTexture.wrapU = this.wrapU;
  59494. newTexture.wrapV = this.wrapV;
  59495. newTexture.coordinatesIndex = this.coordinatesIndex;
  59496. newTexture.coordinatesMode = this.coordinatesMode;
  59497. return newTexture;
  59498. };
  59499. // Methods
  59500. HDRCubeTexture.prototype.delayLoad = function () {
  59501. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  59502. return;
  59503. }
  59504. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  59505. this._texture = this._getFromCache(this.url, this._noMipmap);
  59506. if (!this._texture) {
  59507. this.loadTexture();
  59508. }
  59509. };
  59510. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  59511. return this._textureMatrix;
  59512. };
  59513. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  59514. var texture = null;
  59515. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  59516. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  59517. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, texture.generateHarmonics, texture.useInGammaSpace, texture.usePMREMGenerator);
  59518. texture.name = parsedTexture.name;
  59519. texture.hasAlpha = parsedTexture.hasAlpha;
  59520. texture.level = parsedTexture.level;
  59521. texture.coordinatesMode = parsedTexture.coordinatesMode;
  59522. }
  59523. return texture;
  59524. };
  59525. HDRCubeTexture.prototype.serialize = function () {
  59526. if (!this.name) {
  59527. return null;
  59528. }
  59529. var serializationObject = {};
  59530. serializationObject.name = this.name;
  59531. serializationObject.hasAlpha = this.hasAlpha;
  59532. serializationObject.isCube = true;
  59533. serializationObject.level = this.level;
  59534. serializationObject.size = this._size;
  59535. serializationObject.coordinatesMode = this.coordinatesMode;
  59536. serializationObject.useInGammaSpace = this._useInGammaSpace;
  59537. serializationObject.generateHarmonics = this._generateHarmonics;
  59538. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  59539. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  59540. serializationObject.customType = "BABYLON.HDRCubeTexture";
  59541. return serializationObject;
  59542. };
  59543. /**
  59544. * Saves as a file the data contained in the texture in a binary format.
  59545. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59546. * as the spherical used in the lighting.
  59547. * @param url The HDR file url.
  59548. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59549. * @param onError Method called if any error happens during download.
  59550. * @return The packed binary data.
  59551. */
  59552. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  59553. if (onError === void 0) { onError = null; }
  59554. var callback = function (buffer) {
  59555. var data = new Blob([buffer], { type: 'application/octet-stream' });
  59556. // Returns a URL you can use as a href.
  59557. var objUrl = window.URL.createObjectURL(data);
  59558. // Simulates a link to it and click to dowload.
  59559. var a = document.createElement("a");
  59560. document.body.appendChild(a);
  59561. a.style.display = "none";
  59562. a.href = objUrl;
  59563. a.download = "envmap.babylon.hdr";
  59564. a.click();
  59565. };
  59566. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  59567. };
  59568. /**
  59569. * Serializes the data contained in the texture in a binary format.
  59570. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  59571. * as the spherical used in the lighting.
  59572. * @param url The HDR file url.
  59573. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  59574. * @param onError Method called if any error happens during download.
  59575. * @return The packed binary data.
  59576. */
  59577. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  59578. if (onError === void 0) { onError = null; }
  59579. // Needs the url tho create the texture.
  59580. if (!url) {
  59581. return null;
  59582. }
  59583. // Check Power of two size.
  59584. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  59585. return null;
  59586. }
  59587. var getDataCallback = function (dataBuffer) {
  59588. // Extract the raw linear data.
  59589. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  59590. // Generate harmonics if needed.
  59591. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  59592. // Generate seamless faces
  59593. var mipGeneratorArray = [];
  59594. // Data are known to be in +X +Y +Z -X -Y -Z
  59595. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  59596. mipGeneratorArray.push(cubeData.right); // +X
  59597. mipGeneratorArray.push(cubeData.left); // -X
  59598. mipGeneratorArray.push(cubeData.up); // +Y
  59599. mipGeneratorArray.push(cubeData.down); // -Y
  59600. mipGeneratorArray.push(cubeData.front); // +Z
  59601. mipGeneratorArray.push(cubeData.back); // -Z
  59602. // Custom setup of the generator matching with the PBR shader values.
  59603. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  59604. var mippedData = generator.filterCubeMap();
  59605. // Compute required byte length.
  59606. var byteLength = 1 * 4; // Raw Data Version int32.
  59607. byteLength += 4; // CubeMap max mip face size int32.
  59608. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  59609. // Add data size.
  59610. byteLength += 4; // Number of mip levels int32.
  59611. for (var level = 0; level < mippedData.length; level++) {
  59612. var mipSize = size >> level;
  59613. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  59614. }
  59615. // Prepare binary structure.
  59616. var buffer = new ArrayBuffer(byteLength);
  59617. var intArrayView = new Int32Array(buffer);
  59618. var floatArrayView = new Float32Array(buffer);
  59619. // Fill header.
  59620. intArrayView[0] = 1; // Version 1.
  59621. intArrayView[1] = size; // CubeMap max mip face size.
  59622. // Fill polynomial information.
  59623. sphericalPolynomial.x.toArray(floatArrayView, 2);
  59624. sphericalPolynomial.y.toArray(floatArrayView, 5);
  59625. sphericalPolynomial.z.toArray(floatArrayView, 8);
  59626. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  59627. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  59628. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  59629. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  59630. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  59631. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  59632. // Fill pixel data.
  59633. intArrayView[29] = mippedData.length; // Number of mip levels.
  59634. var startIndex = 30;
  59635. for (var level = 0; level < mippedData.length; level++) {
  59636. // Fill each pixel of the mip level.
  59637. var faceSize = Math.pow(size >> level, 2) * 3;
  59638. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  59639. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  59640. startIndex += faceSize;
  59641. }
  59642. }
  59643. // Callback.
  59644. callback(buffer);
  59645. };
  59646. // Download and process.
  59647. BABYLON.Tools.LoadFile(url, function (data) {
  59648. getDataCallback(data);
  59649. }, null, null, true, onError);
  59650. };
  59651. HDRCubeTexture._facesMapping = [
  59652. "right",
  59653. "up",
  59654. "front",
  59655. "left",
  59656. "down",
  59657. "back"
  59658. ];
  59659. return HDRCubeTexture;
  59660. }(BABYLON.BaseTexture));
  59661. BABYLON.HDRCubeTexture = HDRCubeTexture;
  59662. })(BABYLON || (BABYLON = {}));
  59663. var BABYLON;
  59664. (function (BABYLON) {
  59665. var Debug;
  59666. (function (Debug) {
  59667. /**
  59668. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  59669. */
  59670. var SkeletonViewer = (function () {
  59671. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  59672. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  59673. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  59674. this.skeleton = skeleton;
  59675. this.mesh = mesh;
  59676. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  59677. this.renderingGroupId = renderingGroupId;
  59678. this.color = BABYLON.Color3.White();
  59679. this._debugLines = [];
  59680. this._isEnabled = false;
  59681. this._scene = scene;
  59682. this.update();
  59683. this._renderFunction = this.update.bind(this);
  59684. }
  59685. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  59686. get: function () {
  59687. return this._isEnabled;
  59688. },
  59689. set: function (value) {
  59690. if (this._isEnabled === value) {
  59691. return;
  59692. }
  59693. this._isEnabled = value;
  59694. if (value) {
  59695. this._scene.registerBeforeRender(this._renderFunction);
  59696. }
  59697. else {
  59698. this._scene.unregisterBeforeRender(this._renderFunction);
  59699. }
  59700. },
  59701. enumerable: true,
  59702. configurable: true
  59703. });
  59704. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  59705. if (x === void 0) { x = 0; }
  59706. if (y === void 0) { y = 0; }
  59707. if (z === void 0) { z = 0; }
  59708. var tmat = BABYLON.Tmp.Matrix[0];
  59709. var parentBone = bone.getParent();
  59710. tmat.copyFrom(bone.getLocalMatrix());
  59711. if (x !== 0 || y !== 0 || z !== 0) {
  59712. var tmat2 = BABYLON.Tmp.Matrix[1];
  59713. BABYLON.Matrix.IdentityToRef(tmat2);
  59714. tmat2.m[12] = x;
  59715. tmat2.m[13] = y;
  59716. tmat2.m[14] = z;
  59717. tmat2.multiplyToRef(tmat, tmat);
  59718. }
  59719. if (parentBone) {
  59720. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  59721. }
  59722. tmat.multiplyToRef(meshMat, tmat);
  59723. position.x = tmat.m[12];
  59724. position.y = tmat.m[13];
  59725. position.z = tmat.m[14];
  59726. };
  59727. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  59728. var len = bones.length;
  59729. for (var i = 0; i < len; i++) {
  59730. var bone = bones[i];
  59731. var points = this._debugLines[i];
  59732. if (!points) {
  59733. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59734. this._debugLines[i] = points;
  59735. }
  59736. this._getBonePosition(points[0], bone, meshMat);
  59737. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  59738. }
  59739. };
  59740. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  59741. var len = bones.length;
  59742. var boneNum = 0;
  59743. for (var i = len - 1; i >= 0; i--) {
  59744. var childBone = bones[i];
  59745. var parentBone = childBone.getParent();
  59746. if (!parentBone) {
  59747. continue;
  59748. }
  59749. var points = this._debugLines[boneNum];
  59750. if (!points) {
  59751. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  59752. this._debugLines[boneNum] = points;
  59753. }
  59754. this._getBonePosition(points[0], childBone, meshMat);
  59755. this._getBonePosition(points[1], parentBone, meshMat);
  59756. boneNum++;
  59757. }
  59758. };
  59759. SkeletonViewer.prototype.update = function () {
  59760. if (this.autoUpdateBonesMatrices) {
  59761. this._updateBoneMatrix(this.skeleton.bones[0]);
  59762. }
  59763. if (this.skeleton.bones[0].length === undefined) {
  59764. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59765. }
  59766. else {
  59767. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  59768. }
  59769. if (!this._debugMesh) {
  59770. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  59771. this._debugMesh.renderingGroupId = this.renderingGroupId;
  59772. }
  59773. else {
  59774. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  59775. }
  59776. this._debugMesh.color = this.color;
  59777. };
  59778. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  59779. if (bone.getParent()) {
  59780. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  59781. }
  59782. var children = bone.children;
  59783. var len = children.length;
  59784. for (var i = 0; i < len; i++) {
  59785. this._updateBoneMatrix(children[i]);
  59786. }
  59787. };
  59788. SkeletonViewer.prototype.dispose = function () {
  59789. if (this._debugMesh) {
  59790. this.isEnabled = false;
  59791. this._debugMesh.dispose();
  59792. this._debugMesh = null;
  59793. }
  59794. };
  59795. return SkeletonViewer;
  59796. }());
  59797. Debug.SkeletonViewer = SkeletonViewer;
  59798. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  59799. })(BABYLON || (BABYLON = {}));
  59800. var BABYLON;
  59801. (function (BABYLON) {
  59802. /**
  59803. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  59804. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  59805. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  59806. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  59807. */
  59808. var ColorCurves = (function () {
  59809. function ColorCurves() {
  59810. this._dirty = true;
  59811. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  59812. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  59813. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59814. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  59815. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  59816. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  59817. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  59818. this._globalHue = 30;
  59819. this._globalDensity = 0;
  59820. this._globalSaturation = 0;
  59821. this._globalExposure = 0;
  59822. this._highlightsHue = 30;
  59823. this._highlightsDensity = 0;
  59824. this._highlightsSaturation = 0;
  59825. this._highlightsExposure = 0;
  59826. this._midtonesHue = 30;
  59827. this._midtonesDensity = 0;
  59828. this._midtonesSaturation = 0;
  59829. this._midtonesExposure = 0;
  59830. this._shadowsHue = 30;
  59831. this._shadowsDensity = 0;
  59832. this._shadowsSaturation = 0;
  59833. this._shadowsExposure = 0;
  59834. }
  59835. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  59836. /**
  59837. * Gets the global Hue value.
  59838. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59839. */
  59840. get: function () {
  59841. return this._globalHue;
  59842. },
  59843. /**
  59844. * Sets the global Hue value.
  59845. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59846. */
  59847. set: function (value) {
  59848. this._globalHue = value;
  59849. this._dirty = true;
  59850. },
  59851. enumerable: true,
  59852. configurable: true
  59853. });
  59854. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  59855. /**
  59856. * Gets the global Density value.
  59857. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59858. * Values less than zero provide a filter of opposite hue.
  59859. */
  59860. get: function () {
  59861. return this._globalDensity;
  59862. },
  59863. /**
  59864. * Sets the global Density value.
  59865. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59866. * Values less than zero provide a filter of opposite hue.
  59867. */
  59868. set: function (value) {
  59869. this._globalDensity = value;
  59870. this._dirty = true;
  59871. },
  59872. enumerable: true,
  59873. configurable: true
  59874. });
  59875. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  59876. /**
  59877. * Gets the global Saturation value.
  59878. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  59879. */
  59880. get: function () {
  59881. return this._globalSaturation;
  59882. },
  59883. /**
  59884. * Sets the global Saturation value.
  59885. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  59886. */
  59887. set: function (value) {
  59888. this._globalSaturation = value;
  59889. this._dirty = true;
  59890. },
  59891. enumerable: true,
  59892. configurable: true
  59893. });
  59894. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  59895. /**
  59896. * Gets the highlights Hue value.
  59897. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59898. */
  59899. get: function () {
  59900. return this._highlightsHue;
  59901. },
  59902. /**
  59903. * Sets the highlights Hue value.
  59904. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59905. */
  59906. set: function (value) {
  59907. this._highlightsHue = value;
  59908. this._dirty = true;
  59909. },
  59910. enumerable: true,
  59911. configurable: true
  59912. });
  59913. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  59914. /**
  59915. * Gets the highlights Density value.
  59916. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59917. * Values less than zero provide a filter of opposite hue.
  59918. */
  59919. get: function () {
  59920. return this._highlightsDensity;
  59921. },
  59922. /**
  59923. * Sets the highlights Density value.
  59924. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59925. * Values less than zero provide a filter of opposite hue.
  59926. */
  59927. set: function (value) {
  59928. this._highlightsDensity = value;
  59929. this._dirty = true;
  59930. },
  59931. enumerable: true,
  59932. configurable: true
  59933. });
  59934. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  59935. /**
  59936. * Gets the highlights Saturation value.
  59937. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  59938. */
  59939. get: function () {
  59940. return this._highlightsSaturation;
  59941. },
  59942. /**
  59943. * Sets the highlights Saturation value.
  59944. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  59945. */
  59946. set: function (value) {
  59947. this._highlightsSaturation = value;
  59948. this._dirty = true;
  59949. },
  59950. enumerable: true,
  59951. configurable: true
  59952. });
  59953. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  59954. /**
  59955. * Gets the highlights Exposure value.
  59956. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  59957. */
  59958. get: function () {
  59959. return this._highlightsExposure;
  59960. },
  59961. /**
  59962. * Sets the highlights Exposure value.
  59963. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  59964. */
  59965. set: function (value) {
  59966. this._highlightsExposure = value;
  59967. this._dirty = true;
  59968. },
  59969. enumerable: true,
  59970. configurable: true
  59971. });
  59972. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  59973. /**
  59974. * Gets the midtones Hue value.
  59975. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59976. */
  59977. get: function () {
  59978. return this._midtonesHue;
  59979. },
  59980. /**
  59981. * Sets the midtones Hue value.
  59982. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  59983. */
  59984. set: function (value) {
  59985. this._midtonesHue = value;
  59986. this._dirty = true;
  59987. },
  59988. enumerable: true,
  59989. configurable: true
  59990. });
  59991. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  59992. /**
  59993. * Gets the midtones Density value.
  59994. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  59995. * Values less than zero provide a filter of opposite hue.
  59996. */
  59997. get: function () {
  59998. return this._midtonesDensity;
  59999. },
  60000. /**
  60001. * Sets the midtones Density value.
  60002. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  60003. * Values less than zero provide a filter of opposite hue.
  60004. */
  60005. set: function (value) {
  60006. this._midtonesDensity = value;
  60007. this._dirty = true;
  60008. },
  60009. enumerable: true,
  60010. configurable: true
  60011. });
  60012. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  60013. /**
  60014. * Gets the midtones Saturation value.
  60015. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  60016. */
  60017. get: function () {
  60018. return this._midtonesSaturation;
  60019. },
  60020. /**
  60021. * Sets the midtones Saturation value.
  60022. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  60023. */
  60024. set: function (value) {
  60025. this._midtonesSaturation = value;
  60026. this._dirty = true;
  60027. },
  60028. enumerable: true,
  60029. configurable: true
  60030. });
  60031. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  60032. /**
  60033. * Gets the midtones Exposure value.
  60034. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  60035. */
  60036. get: function () {
  60037. return this._midtonesExposure;
  60038. },
  60039. /**
  60040. * Sets the midtones Exposure value.
  60041. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  60042. */
  60043. set: function (value) {
  60044. this._midtonesExposure = value;
  60045. this._dirty = true;
  60046. },
  60047. enumerable: true,
  60048. configurable: true
  60049. });
  60050. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  60051. /**
  60052. * Gets the shadows Hue value.
  60053. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  60054. */
  60055. get: function () {
  60056. return this._shadowsHue;
  60057. },
  60058. /**
  60059. * Sets the shadows Hue value.
  60060. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  60061. */
  60062. set: function (value) {
  60063. this._shadowsHue = value;
  60064. this._dirty = true;
  60065. },
  60066. enumerable: true,
  60067. configurable: true
  60068. });
  60069. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  60070. /**
  60071. * Gets the shadows Density value.
  60072. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  60073. * Values less than zero provide a filter of opposite hue.
  60074. */
  60075. get: function () {
  60076. return this._shadowsDensity;
  60077. },
  60078. /**
  60079. * Sets the shadows Density value.
  60080. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  60081. * Values less than zero provide a filter of opposite hue.
  60082. */
  60083. set: function (value) {
  60084. this._shadowsDensity = value;
  60085. this._dirty = true;
  60086. },
  60087. enumerable: true,
  60088. configurable: true
  60089. });
  60090. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  60091. /**
  60092. * Gets the shadows Saturation value.
  60093. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  60094. */
  60095. get: function () {
  60096. return this._shadowsSaturation;
  60097. },
  60098. /**
  60099. * Sets the shadows Saturation value.
  60100. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  60101. */
  60102. set: function (value) {
  60103. this._shadowsSaturation = value;
  60104. this._dirty = true;
  60105. },
  60106. enumerable: true,
  60107. configurable: true
  60108. });
  60109. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  60110. /**
  60111. * Gets the shadows Exposure value.
  60112. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  60113. */
  60114. get: function () {
  60115. return this._shadowsExposure;
  60116. },
  60117. /**
  60118. * Sets the shadows Exposure value.
  60119. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  60120. */
  60121. set: function (value) {
  60122. this._shadowsExposure = value;
  60123. this._dirty = true;
  60124. },
  60125. enumerable: true,
  60126. configurable: true
  60127. });
  60128. /**
  60129. * Binds the color curves to the shader.
  60130. * @param colorCurves The color curve to bind
  60131. * @param effect The effect to bind to
  60132. */
  60133. ColorCurves.Bind = function (colorCurves, effect) {
  60134. if (colorCurves._dirty) {
  60135. colorCurves._dirty = false;
  60136. // Fill in global info.
  60137. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  60138. // Compute highlights info.
  60139. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  60140. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  60141. // Compute midtones info.
  60142. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  60143. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  60144. // Compute shadows info.
  60145. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  60146. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  60147. // Compute deltas (neutral is midtones).
  60148. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  60149. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  60150. }
  60151. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  60152. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  60153. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  60154. };
  60155. /**
  60156. * Prepare the list of uniforms associated with the ColorCurves effects.
  60157. * @param uniformsList The list of uniforms used in the effect
  60158. */
  60159. ColorCurves.PrepareUniforms = function (uniformsList) {
  60160. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  60161. };
  60162. /**
  60163. * Returns color grading data based on a hue, density, saturation and exposure value.
  60164. * @param filterHue The hue of the color filter.
  60165. * @param filterDensity The density of the color filter.
  60166. * @param saturation The saturation.
  60167. * @param exposure The exposure.
  60168. * @param result The result data container.
  60169. */
  60170. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  60171. if (hue == null) {
  60172. return;
  60173. }
  60174. hue = ColorCurves.clamp(hue, 0, 360);
  60175. density = ColorCurves.clamp(density, -100, 100);
  60176. saturation = ColorCurves.clamp(saturation, -100, 100);
  60177. exposure = ColorCurves.clamp(exposure, -100, 100);
  60178. // Remap the slider/config filter density with non-linear mapping and also scale by half
  60179. // so that the maximum filter density is only 50% control. This provides fine control
  60180. // for small values and reasonable range.
  60181. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  60182. density *= 0.5;
  60183. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  60184. if (density < 0) {
  60185. density *= -1;
  60186. hue = (hue + 180) % 360;
  60187. }
  60188. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  60189. result.scaleToRef(2, result);
  60190. result.a = 1 + 0.01 * saturation;
  60191. };
  60192. /**
  60193. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  60194. * @param value The input slider value in range [-100,100].
  60195. * @returns Adjusted value.
  60196. */
  60197. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  60198. value /= 100;
  60199. var x = Math.abs(value);
  60200. x = Math.pow(x, 2);
  60201. if (value < 0) {
  60202. x *= -1;
  60203. }
  60204. x *= 100;
  60205. return x;
  60206. };
  60207. /**
  60208. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  60209. * @param hue The hue (H) input.
  60210. * @param saturation The saturation (S) input.
  60211. * @param brightness The brightness (B) input.
  60212. * @result An RGBA color represented as Vector4.
  60213. */
  60214. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  60215. var h = ColorCurves.clamp(hue, 0, 360);
  60216. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  60217. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  60218. if (s === 0) {
  60219. result.r = v;
  60220. result.g = v;
  60221. result.b = v;
  60222. }
  60223. else {
  60224. // sector 0 to 5
  60225. h /= 60;
  60226. var i = Math.floor(h);
  60227. // fractional part of h
  60228. var f = h - i;
  60229. var p = v * (1 - s);
  60230. var q = v * (1 - s * f);
  60231. var t = v * (1 - s * (1 - f));
  60232. switch (i) {
  60233. case 0:
  60234. result.r = v;
  60235. result.g = t;
  60236. result.b = p;
  60237. break;
  60238. case 1:
  60239. result.r = q;
  60240. result.g = v;
  60241. result.b = p;
  60242. break;
  60243. case 2:
  60244. result.r = p;
  60245. result.g = v;
  60246. result.b = t;
  60247. break;
  60248. case 3:
  60249. result.r = p;
  60250. result.g = q;
  60251. result.b = v;
  60252. break;
  60253. case 4:
  60254. result.r = t;
  60255. result.g = p;
  60256. result.b = v;
  60257. break;
  60258. default:
  60259. result.r = v;
  60260. result.g = p;
  60261. result.b = q;
  60262. break;
  60263. }
  60264. }
  60265. result.a = 1;
  60266. };
  60267. /**
  60268. * Returns a value clamped between min and max
  60269. * @param value The value to clamp
  60270. * @param min The minimum of value
  60271. * @param max The maximum of value
  60272. * @returns The clamped value.
  60273. */
  60274. ColorCurves.clamp = function (value, min, max) {
  60275. return Math.min(Math.max(value, min), max);
  60276. };
  60277. /**
  60278. * Clones the current color curve instance.
  60279. * @return The cloned curves
  60280. */
  60281. ColorCurves.prototype.clone = function () {
  60282. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  60283. };
  60284. /**
  60285. * Serializes the current color curve instance to a json representation.
  60286. * @return a JSON representation
  60287. */
  60288. ColorCurves.prototype.serialize = function () {
  60289. return BABYLON.SerializationHelper.Serialize(this);
  60290. };
  60291. /**
  60292. * Parses the color curve from a json representation.
  60293. * @param source the JSON source to parse
  60294. * @return The parsed curves
  60295. */
  60296. ColorCurves.Parse = function (source) {
  60297. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  60298. };
  60299. __decorate([
  60300. BABYLON.serialize()
  60301. ], ColorCurves.prototype, "_globalHue", void 0);
  60302. __decorate([
  60303. BABYLON.serialize()
  60304. ], ColorCurves.prototype, "_globalDensity", void 0);
  60305. __decorate([
  60306. BABYLON.serialize()
  60307. ], ColorCurves.prototype, "_globalSaturation", void 0);
  60308. __decorate([
  60309. BABYLON.serialize()
  60310. ], ColorCurves.prototype, "_globalExposure", void 0);
  60311. __decorate([
  60312. BABYLON.serialize()
  60313. ], ColorCurves.prototype, "_highlightsHue", void 0);
  60314. __decorate([
  60315. BABYLON.serialize()
  60316. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  60317. __decorate([
  60318. BABYLON.serialize()
  60319. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  60320. __decorate([
  60321. BABYLON.serialize()
  60322. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  60323. __decorate([
  60324. BABYLON.serialize()
  60325. ], ColorCurves.prototype, "_midtonesHue", void 0);
  60326. __decorate([
  60327. BABYLON.serialize()
  60328. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  60329. __decorate([
  60330. BABYLON.serialize()
  60331. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  60332. __decorate([
  60333. BABYLON.serialize()
  60334. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  60335. return ColorCurves;
  60336. }());
  60337. BABYLON.ColorCurves = ColorCurves;
  60338. })(BABYLON || (BABYLON = {}));
  60339. var BABYLON;
  60340. (function (BABYLON) {
  60341. /**
  60342. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  60343. * It can help converting any input color in a desired output one. This can then be used to create effects
  60344. * from sepia, black and white to sixties or futuristic rendering...
  60345. *
  60346. * The only supported format is currently 3dl.
  60347. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  60348. */
  60349. var ColorGradingTexture = (function (_super) {
  60350. __extends(ColorGradingTexture, _super);
  60351. /**
  60352. * Instantiates a ColorGradingTexture from the following parameters.
  60353. *
  60354. * @param url The location of the color gradind data (currently only supporting 3dl)
  60355. * @param scene The scene the texture will be used in
  60356. */
  60357. function ColorGradingTexture(url, scene) {
  60358. _super.call(this, scene);
  60359. if (!url) {
  60360. return;
  60361. }
  60362. this._textureMatrix = BABYLON.Matrix.Identity();
  60363. this.name = url;
  60364. this.url = url;
  60365. this.hasAlpha = false;
  60366. this.isCube = false;
  60367. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60368. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60369. this.anisotropicFilteringLevel = 1;
  60370. this._texture = this._getFromCache(url, true);
  60371. if (!this._texture) {
  60372. if (!scene.useDelayedTextureLoading) {
  60373. this.loadTexture();
  60374. }
  60375. else {
  60376. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  60377. }
  60378. }
  60379. }
  60380. /**
  60381. * Returns the texture matrix used in most of the material.
  60382. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  60383. */
  60384. ColorGradingTexture.prototype.getTextureMatrix = function () {
  60385. return this._textureMatrix;
  60386. };
  60387. /**
  60388. * Occurs when the file being loaded is a .3dl LUT file.
  60389. */
  60390. ColorGradingTexture.prototype.load3dlTexture = function () {
  60391. var _this = this;
  60392. var mipLevels = 0;
  60393. var floatArrayView = null;
  60394. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  60395. this._texture = texture;
  60396. var callback = function (text) {
  60397. var data;
  60398. var tempData;
  60399. var line;
  60400. var lines = text.split('\n');
  60401. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  60402. var maxColor = 0;
  60403. for (var i = 0; i < lines.length; i++) {
  60404. line = lines[i];
  60405. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  60406. continue;
  60407. if (line.indexOf('#') === 0)
  60408. continue;
  60409. var words = line.split(" ");
  60410. if (size === 0) {
  60411. // Number of space + one
  60412. size = words.length;
  60413. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  60414. tempData = new Float32Array(size * size * size * 4);
  60415. continue;
  60416. }
  60417. if (size != 0) {
  60418. var r = Math.max(parseInt(words[0]), 0);
  60419. var g = Math.max(parseInt(words[1]), 0);
  60420. var b = Math.max(parseInt(words[2]), 0);
  60421. maxColor = Math.max(r, maxColor);
  60422. maxColor = Math.max(g, maxColor);
  60423. maxColor = Math.max(b, maxColor);
  60424. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  60425. tempData[pixelStorageIndex + 0] = r;
  60426. tempData[pixelStorageIndex + 1] = g;
  60427. tempData[pixelStorageIndex + 2] = b;
  60428. tempData[pixelStorageIndex + 3] = 0;
  60429. pixelIndexSlice++;
  60430. if (pixelIndexSlice % size == 0) {
  60431. pixelIndexH++;
  60432. pixelIndexSlice = 0;
  60433. if (pixelIndexH % size == 0) {
  60434. pixelIndexW++;
  60435. pixelIndexH = 0;
  60436. }
  60437. }
  60438. }
  60439. }
  60440. for (var i = 0; i < tempData.length; i++) {
  60441. var value = tempData[i];
  60442. data[i] = (value / maxColor * 255);
  60443. }
  60444. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  60445. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  60446. };
  60447. BABYLON.Tools.LoadFile(this.url, callback);
  60448. return this._texture;
  60449. };
  60450. /**
  60451. * Starts the loading process of the texture.
  60452. */
  60453. ColorGradingTexture.prototype.loadTexture = function () {
  60454. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  60455. this.load3dlTexture();
  60456. }
  60457. };
  60458. /**
  60459. * Clones the color gradind texture.
  60460. */
  60461. ColorGradingTexture.prototype.clone = function () {
  60462. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  60463. // Base texture
  60464. newTexture.level = this.level;
  60465. return newTexture;
  60466. };
  60467. /**
  60468. * Called during delayed load for textures.
  60469. */
  60470. ColorGradingTexture.prototype.delayLoad = function () {
  60471. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  60472. return;
  60473. }
  60474. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  60475. this._texture = this._getFromCache(this.url, true);
  60476. if (!this._texture) {
  60477. this.loadTexture();
  60478. }
  60479. };
  60480. /**
  60481. * Binds the color grading to the shader.
  60482. * @param colorGrading The texture to bind
  60483. * @param effect The effect to bind to
  60484. */
  60485. ColorGradingTexture.Bind = function (colorGrading, effect) {
  60486. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  60487. var x = colorGrading.level; // Texture Level
  60488. var y = colorGrading.getSize().height; // Texture Size example with 8
  60489. var z = y - 1.0; // SizeMinusOne 8 - 1
  60490. var w = 1 / y; // Space of 1 slice 1 / 8
  60491. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  60492. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  60493. var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8 // Space of 1 pixel in V direction, e.g. 1/8
  60494. var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  60495. var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  60496. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  60497. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  60498. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  60499. };
  60500. /**
  60501. * Prepare the list of uniforms associated with the ColorGrading effects.
  60502. * @param uniformsList The list of uniforms used in the effect
  60503. * @param samplersList The list of samplers used in the effect
  60504. */
  60505. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  60506. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  60507. samplersList.push("cameraColorGrading2DSampler");
  60508. };
  60509. /**
  60510. * Parses a color grading texture serialized by Babylon.
  60511. * @param parsedTexture The texture information being parsedTexture
  60512. * @param scene The scene to load the texture in
  60513. * @param rootUrl The root url of the data assets to load
  60514. * @return A color gradind texture
  60515. */
  60516. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  60517. var texture = null;
  60518. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  60519. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  60520. texture.name = parsedTexture.name;
  60521. texture.level = parsedTexture.level;
  60522. }
  60523. return texture;
  60524. };
  60525. /**
  60526. * Serializes the LUT texture to json format.
  60527. */
  60528. ColorGradingTexture.prototype.serialize = function () {
  60529. if (!this.name) {
  60530. return null;
  60531. }
  60532. var serializationObject = {};
  60533. serializationObject.name = this.name;
  60534. serializationObject.level = this.level;
  60535. serializationObject.customType = "BABYLON.ColorGradingTexture";
  60536. return serializationObject;
  60537. };
  60538. /**
  60539. * Empty line regex stored for GC.
  60540. */
  60541. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  60542. return ColorGradingTexture;
  60543. }(BABYLON.BaseTexture));
  60544. BABYLON.ColorGradingTexture = ColorGradingTexture;
  60545. })(BABYLON || (BABYLON = {}));
  60546. var BABYLON;
  60547. (function (BABYLON) {
  60548. var PBRMaterialDefines = (function (_super) {
  60549. __extends(PBRMaterialDefines, _super);
  60550. function PBRMaterialDefines() {
  60551. _super.call(this);
  60552. this.ALBEDO = false;
  60553. this.AMBIENT = false;
  60554. this.OPACITY = false;
  60555. this.OPACITYRGB = false;
  60556. this.REFLECTION = false;
  60557. this.EMISSIVE = false;
  60558. this.REFLECTIVITY = false;
  60559. this.BUMP = false;
  60560. this.PARALLAX = false;
  60561. this.PARALLAXOCCLUSION = false;
  60562. this.SPECULAROVERALPHA = false;
  60563. this.CLIPPLANE = false;
  60564. this.ALPHATEST = false;
  60565. this.ALPHAFROMALBEDO = false;
  60566. this.POINTSIZE = false;
  60567. this.FOG = false;
  60568. this.SPECULARTERM = false;
  60569. this.OPACITYFRESNEL = false;
  60570. this.EMISSIVEFRESNEL = false;
  60571. this.FRESNEL = false;
  60572. this.NORMAL = false;
  60573. this.UV1 = false;
  60574. this.UV2 = false;
  60575. this.VERTEXCOLOR = false;
  60576. this.VERTEXALPHA = false;
  60577. this.NUM_BONE_INFLUENCERS = 0;
  60578. this.BonesPerMesh = 0;
  60579. this.INSTANCES = false;
  60580. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  60581. this.MICROSURFACEAUTOMATIC = false;
  60582. this.EMISSIVEASILLUMINATION = false;
  60583. this.LINKEMISSIVEWITHALBEDO = false;
  60584. this.LIGHTMAP = false;
  60585. this.USELIGHTMAPASSHADOWMAP = false;
  60586. this.REFLECTIONMAP_3D = false;
  60587. this.REFLECTIONMAP_SPHERICAL = false;
  60588. this.REFLECTIONMAP_PLANAR = false;
  60589. this.REFLECTIONMAP_CUBIC = false;
  60590. this.REFLECTIONMAP_PROJECTION = false;
  60591. this.REFLECTIONMAP_SKYBOX = false;
  60592. this.REFLECTIONMAP_EXPLICIT = false;
  60593. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  60594. this.INVERTCUBICMAP = false;
  60595. this.LOGARITHMICDEPTH = false;
  60596. this.CAMERATONEMAP = false;
  60597. this.CAMERACONTRAST = false;
  60598. this.CAMERACOLORGRADING = false;
  60599. this.CAMERACOLORCURVES = false;
  60600. this.OVERLOADEDVALUES = false;
  60601. this.OVERLOADEDSHADOWVALUES = false;
  60602. this.USESPHERICALFROMREFLECTIONMAP = false;
  60603. this.REFRACTION = false;
  60604. this.REFRACTIONMAP_3D = false;
  60605. this.LINKREFRACTIONTOTRANSPARENCY = false;
  60606. this.REFRACTIONMAPINLINEARSPACE = false;
  60607. this.LODBASEDMICROSFURACE = false;
  60608. this.USEPHYSICALLIGHTFALLOFF = false;
  60609. this.RADIANCEOVERALPHA = false;
  60610. this.USEPMREMREFLECTION = false;
  60611. this.USEPMREMREFRACTION = false;
  60612. this.OPENGLNORMALMAP = false;
  60613. this.INVERTNORMALMAPX = false;
  60614. this.INVERTNORMALMAPY = false;
  60615. this.SHADOWFULLFLOAT = false;
  60616. this.rebuild();
  60617. }
  60618. return PBRMaterialDefines;
  60619. }(BABYLON.MaterialDefines));
  60620. /**
  60621. * The Physically based material of BJS.
  60622. *
  60623. * This offers the main features of a standard PBR material.
  60624. * For more information, please refer to the documentation :
  60625. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  60626. */
  60627. var PBRMaterial = (function (_super) {
  60628. __extends(PBRMaterial, _super);
  60629. /**
  60630. * Instantiates a new PBRMaterial instance.
  60631. *
  60632. * @param name The material name
  60633. * @param scene The scene the material will be use in.
  60634. */
  60635. function PBRMaterial(name, scene) {
  60636. var _this = this;
  60637. _super.call(this, name, scene);
  60638. /**
  60639. * Intensity of the direct lights e.g. the four lights available in your scene.
  60640. * This impacts both the direct diffuse and specular highlights.
  60641. */
  60642. this.directIntensity = 1.0;
  60643. /**
  60644. * Intensity of the emissive part of the material.
  60645. * This helps controlling the emissive effect without modifying the emissive color.
  60646. */
  60647. this.emissiveIntensity = 1.0;
  60648. /**
  60649. * Intensity of the environment e.g. how much the environment will light the object
  60650. * either through harmonics for rough material or through the refelction for shiny ones.
  60651. */
  60652. this.environmentIntensity = 1.0;
  60653. /**
  60654. * This is a special control allowing the reduction of the specular highlights coming from the
  60655. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  60656. */
  60657. this.specularIntensity = 1.0;
  60658. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  60659. /**
  60660. * Debug Control allowing disabling the bump map on this material.
  60661. */
  60662. this.disableBumpMap = false;
  60663. /**
  60664. * Debug Control helping enforcing or dropping the darkness of shadows.
  60665. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  60666. */
  60667. this.overloadedShadowIntensity = 1.0;
  60668. /**
  60669. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  60670. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  60671. */
  60672. this.overloadedShadeIntensity = 1.0;
  60673. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  60674. /**
  60675. * The camera exposure used on this material.
  60676. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  60677. * This corresponds to a photographic exposure.
  60678. */
  60679. this.cameraExposure = 1.0;
  60680. /**
  60681. * The camera contrast used on this material.
  60682. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  60683. */
  60684. this.cameraContrast = 1.0;
  60685. /**
  60686. * Color Grading 2D Lookup Texture.
  60687. * This allows special effects like sepia, black and white to sixties rendering style.
  60688. */
  60689. this.cameraColorGradingTexture = null;
  60690. /**
  60691. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  60692. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  60693. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  60694. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  60695. */
  60696. this.cameraColorCurves = null;
  60697. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  60698. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  60699. /**
  60700. * Debug Control allowing to overload the ambient color.
  60701. * This as to be use with the overloadedAmbientIntensity parameter.
  60702. */
  60703. this.overloadedAmbient = BABYLON.Color3.White();
  60704. /**
  60705. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  60706. */
  60707. this.overloadedAmbientIntensity = 0.0;
  60708. /**
  60709. * Debug Control allowing to overload the albedo color.
  60710. * This as to be use with the overloadedAlbedoIntensity parameter.
  60711. */
  60712. this.overloadedAlbedo = BABYLON.Color3.White();
  60713. /**
  60714. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  60715. */
  60716. this.overloadedAlbedoIntensity = 0.0;
  60717. /**
  60718. * Debug Control allowing to overload the reflectivity color.
  60719. * This as to be use with the overloadedReflectivityIntensity parameter.
  60720. */
  60721. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  60722. /**
  60723. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  60724. */
  60725. this.overloadedReflectivityIntensity = 0.0;
  60726. /**
  60727. * Debug Control allowing to overload the emissive color.
  60728. * This as to be use with the overloadedEmissiveIntensity parameter.
  60729. */
  60730. this.overloadedEmissive = BABYLON.Color3.White();
  60731. /**
  60732. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  60733. */
  60734. this.overloadedEmissiveIntensity = 0.0;
  60735. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  60736. /**
  60737. * Debug Control allowing to overload the reflection color.
  60738. * This as to be use with the overloadedReflectionIntensity parameter.
  60739. */
  60740. this.overloadedReflection = BABYLON.Color3.White();
  60741. /**
  60742. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  60743. */
  60744. this.overloadedReflectionIntensity = 0.0;
  60745. /**
  60746. * Debug Control allowing to overload the microsurface.
  60747. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  60748. */
  60749. this.overloadedMicroSurface = 0.0;
  60750. /**
  60751. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  60752. */
  60753. this.overloadedMicroSurfaceIntensity = 0.0;
  60754. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  60755. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  60756. /**
  60757. * AKA Diffuse Color in other nomenclature.
  60758. */
  60759. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  60760. /**
  60761. * AKA Specular Color in other nomenclature.
  60762. */
  60763. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  60764. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  60765. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  60766. /**
  60767. * AKA Glossiness in other nomenclature.
  60768. */
  60769. this.microSurface = 0.9;
  60770. /**
  60771. * source material index of refraction (IOR)' / 'destination material IOR.
  60772. */
  60773. this.indexOfRefraction = 0.66;
  60774. /**
  60775. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  60776. */
  60777. this.invertRefractionY = false;
  60778. /**
  60779. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  60780. * Materials half opaque for instance using refraction could benefit from this control.
  60781. */
  60782. this.linkRefractionWithTransparency = false;
  60783. /**
  60784. * The emissive and albedo are linked to never be more than one (Energy conservation).
  60785. */
  60786. this.linkEmissiveWithAlbedo = false;
  60787. this.useLightmapAsShadowmap = false;
  60788. /**
  60789. * In this mode, the emissive informtaion will always be added to the lighting once.
  60790. * A light for instance can be thought as emissive.
  60791. */
  60792. this.useEmissiveAsIllumination = false;
  60793. /**
  60794. * Secifies that the alpha is coming form the albedo channel alpha channel.
  60795. */
  60796. this.useAlphaFromAlbedoTexture = false;
  60797. /**
  60798. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  60799. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  60800. */
  60801. this.useSpecularOverAlpha = true;
  60802. /**
  60803. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  60804. */
  60805. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  60806. /**
  60807. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  60808. * The material will try to infer what glossiness each pixel should be.
  60809. */
  60810. this.useAutoMicroSurfaceFromReflectivityMap = false;
  60811. /**
  60812. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  60813. * the creation of the material.
  60814. */
  60815. this.useScalarInLinearSpace = false;
  60816. /**
  60817. * BJS is using an harcoded light falloff based on a manually sets up range.
  60818. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  60819. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  60820. */
  60821. this.usePhysicalLightFalloff = true;
  60822. /**
  60823. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  60824. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  60825. */
  60826. this.useRadianceOverAlpha = true;
  60827. /**
  60828. * Allows using the bump map in parallax mode.
  60829. */
  60830. this.useParallax = false;
  60831. /**
  60832. * Allows using the bump map in parallax occlusion mode.
  60833. */
  60834. this.useParallaxOcclusion = false;
  60835. /**
  60836. * Controls the scale bias of the parallax mode.
  60837. */
  60838. this.parallaxScaleBias = 0.05;
  60839. /**
  60840. * If sets to true, disables all the lights affecting the material.
  60841. */
  60842. this.disableLighting = false;
  60843. /**
  60844. * Number of Simultaneous lights allowed on the material.
  60845. */
  60846. this.maxSimultaneousLights = 4;
  60847. /**
  60848. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  60849. */
  60850. this.invertNormalMapX = false;
  60851. /**
  60852. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  60853. */
  60854. this.invertNormalMapY = false;
  60855. this._renderTargets = new BABYLON.SmartArray(16);
  60856. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  60857. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  60858. this._tempColor = new BABYLON.Color3();
  60859. this._defines = new PBRMaterialDefines();
  60860. this._cachedDefines = new PBRMaterialDefines();
  60861. this._myScene = null;
  60862. this._myShadowGenerator = null;
  60863. this._cachedDefines.BonesPerMesh = -1;
  60864. this.getRenderTargetTextures = function () {
  60865. _this._renderTargets.reset();
  60866. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  60867. _this._renderTargets.push(_this.reflectionTexture);
  60868. }
  60869. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  60870. _this._renderTargets.push(_this.refractionTexture);
  60871. }
  60872. return _this._renderTargets;
  60873. };
  60874. }
  60875. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  60876. get: function () {
  60877. return this._useLogarithmicDepth;
  60878. },
  60879. set: function (value) {
  60880. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  60881. },
  60882. enumerable: true,
  60883. configurable: true
  60884. });
  60885. PBRMaterial.prototype.needAlphaBlending = function () {
  60886. if (this.linkRefractionWithTransparency) {
  60887. return false;
  60888. }
  60889. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  60890. };
  60891. PBRMaterial.prototype.needAlphaTesting = function () {
  60892. if (this.linkRefractionWithTransparency) {
  60893. return false;
  60894. }
  60895. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  60896. };
  60897. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  60898. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  60899. };
  60900. PBRMaterial.prototype.getAlphaTestTexture = function () {
  60901. return this.albedoTexture;
  60902. };
  60903. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  60904. if (!mesh) {
  60905. return true;
  60906. }
  60907. if (this._defines.INSTANCES !== useInstances) {
  60908. return false;
  60909. }
  60910. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  60911. return true;
  60912. }
  60913. return false;
  60914. };
  60915. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  60916. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  60917. };
  60918. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  60919. if (!useScalarInLinear) {
  60920. color.toLinearSpaceToRef(ref);
  60921. }
  60922. else {
  60923. ref.r = color.r;
  60924. ref.g = color.g;
  60925. ref.b = color.b;
  60926. }
  60927. };
  60928. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  60929. var lightIndex = 0;
  60930. var depthValuesAlreadySet = false;
  60931. for (var index = 0; index < scene.lights.length; index++) {
  60932. var light = scene.lights[index];
  60933. if (!light.isEnabled()) {
  60934. continue;
  60935. }
  60936. if (!light.canAffectMesh(mesh)) {
  60937. continue;
  60938. }
  60939. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  60940. // GAMMA CORRECTION.
  60941. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  60942. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  60943. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  60944. if (defines["SPECULARTERM"]) {
  60945. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  60946. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  60947. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  60948. }
  60949. // Shadows
  60950. if (scene.shadowsEnabled) {
  60951. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  60952. }
  60953. lightIndex++;
  60954. if (lightIndex === maxSimultaneousLights)
  60955. break;
  60956. }
  60957. };
  60958. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  60959. if (this.checkReadyOnlyOnce) {
  60960. if (this._wasPreviouslyReady) {
  60961. return true;
  60962. }
  60963. }
  60964. var scene = this.getScene();
  60965. if (!this.checkReadyOnEveryCall) {
  60966. if (this._renderId === scene.getRenderId()) {
  60967. if (this._checkCache(scene, mesh, useInstances)) {
  60968. return true;
  60969. }
  60970. }
  60971. }
  60972. var engine = scene.getEngine();
  60973. var needNormals = false;
  60974. var needUVs = false;
  60975. this._defines.reset();
  60976. if (scene.texturesEnabled) {
  60977. // Textures
  60978. if (scene.texturesEnabled) {
  60979. if (scene.getEngine().getCaps().textureLOD) {
  60980. this._defines.LODBASEDMICROSFURACE = true;
  60981. }
  60982. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  60983. if (!this.albedoTexture.isReady()) {
  60984. return false;
  60985. }
  60986. else {
  60987. needUVs = true;
  60988. this._defines.ALBEDO = true;
  60989. }
  60990. }
  60991. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  60992. if (!this.ambientTexture.isReady()) {
  60993. return false;
  60994. }
  60995. else {
  60996. needUVs = true;
  60997. this._defines.AMBIENT = true;
  60998. }
  60999. }
  61000. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  61001. if (!this.opacityTexture.isReady()) {
  61002. return false;
  61003. }
  61004. else {
  61005. needUVs = true;
  61006. this._defines.OPACITY = true;
  61007. if (this.opacityTexture.getAlphaFromRGB) {
  61008. this._defines.OPACITYRGB = true;
  61009. }
  61010. }
  61011. }
  61012. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  61013. if (!this.reflectionTexture.isReady()) {
  61014. return false;
  61015. }
  61016. else {
  61017. needNormals = true;
  61018. this._defines.REFLECTION = true;
  61019. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  61020. this._defines.INVERTCUBICMAP = true;
  61021. }
  61022. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  61023. switch (this.reflectionTexture.coordinatesMode) {
  61024. case BABYLON.Texture.CUBIC_MODE:
  61025. case BABYLON.Texture.INVCUBIC_MODE:
  61026. this._defines.REFLECTIONMAP_CUBIC = true;
  61027. break;
  61028. case BABYLON.Texture.EXPLICIT_MODE:
  61029. this._defines.REFLECTIONMAP_EXPLICIT = true;
  61030. break;
  61031. case BABYLON.Texture.PLANAR_MODE:
  61032. this._defines.REFLECTIONMAP_PLANAR = true;
  61033. break;
  61034. case BABYLON.Texture.PROJECTION_MODE:
  61035. this._defines.REFLECTIONMAP_PROJECTION = true;
  61036. break;
  61037. case BABYLON.Texture.SKYBOX_MODE:
  61038. this._defines.REFLECTIONMAP_SKYBOX = true;
  61039. break;
  61040. case BABYLON.Texture.SPHERICAL_MODE:
  61041. this._defines.REFLECTIONMAP_SPHERICAL = true;
  61042. break;
  61043. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  61044. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  61045. break;
  61046. }
  61047. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  61048. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  61049. needNormals = true;
  61050. if (this.reflectionTexture.isPMREM) {
  61051. this._defines.USEPMREMREFLECTION = true;
  61052. }
  61053. }
  61054. }
  61055. }
  61056. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  61057. if (!this.lightmapTexture.isReady()) {
  61058. return false;
  61059. }
  61060. else {
  61061. needUVs = true;
  61062. this._defines.LIGHTMAP = true;
  61063. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  61064. }
  61065. }
  61066. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  61067. if (!this.emissiveTexture.isReady()) {
  61068. return false;
  61069. }
  61070. else {
  61071. needUVs = true;
  61072. this._defines.EMISSIVE = true;
  61073. }
  61074. }
  61075. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  61076. if (!this.reflectivityTexture.isReady()) {
  61077. return false;
  61078. }
  61079. else {
  61080. needUVs = true;
  61081. this._defines.REFLECTIVITY = true;
  61082. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  61083. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  61084. }
  61085. }
  61086. }
  61087. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  61088. if (!this.bumpTexture.isReady()) {
  61089. return false;
  61090. }
  61091. else {
  61092. needUVs = true;
  61093. this._defines.BUMP = true;
  61094. if (this.useParallax) {
  61095. this._defines.PARALLAX = true;
  61096. if (this.useParallaxOcclusion) {
  61097. this._defines.PARALLAXOCCLUSION = true;
  61098. }
  61099. }
  61100. if (this.invertNormalMapX) {
  61101. this._defines.INVERTNORMALMAPX = true;
  61102. }
  61103. if (this.invertNormalMapY) {
  61104. this._defines.INVERTNORMALMAPY = true;
  61105. }
  61106. }
  61107. }
  61108. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  61109. if (!this.refractionTexture.isReady()) {
  61110. return false;
  61111. }
  61112. else {
  61113. needUVs = true;
  61114. this._defines.REFRACTION = true;
  61115. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  61116. if (this.linkRefractionWithTransparency) {
  61117. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  61118. }
  61119. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  61120. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  61121. if (this.refractionTexture.isPMREM) {
  61122. this._defines.USEPMREMREFRACTION = true;
  61123. }
  61124. }
  61125. }
  61126. }
  61127. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  61128. if (!this.cameraColorGradingTexture.isReady()) {
  61129. return false;
  61130. }
  61131. else {
  61132. this._defines.CAMERACOLORGRADING = true;
  61133. }
  61134. }
  61135. }
  61136. // Effect
  61137. if (scene.clipPlane) {
  61138. this._defines.CLIPPLANE = true;
  61139. }
  61140. if (engine.getAlphaTesting()) {
  61141. this._defines.ALPHATEST = true;
  61142. }
  61143. if (this._shouldUseAlphaFromAlbedoTexture()) {
  61144. this._defines.ALPHAFROMALBEDO = true;
  61145. }
  61146. if (this.useEmissiveAsIllumination) {
  61147. this._defines.EMISSIVEASILLUMINATION = true;
  61148. }
  61149. if (this.linkEmissiveWithAlbedo) {
  61150. this._defines.LINKEMISSIVEWITHALBEDO = true;
  61151. }
  61152. if (this.useLogarithmicDepth) {
  61153. this._defines.LOGARITHMICDEPTH = true;
  61154. }
  61155. if (this.cameraContrast != 1) {
  61156. this._defines.CAMERACONTRAST = true;
  61157. }
  61158. if (this.cameraExposure != 1) {
  61159. this._defines.CAMERATONEMAP = true;
  61160. }
  61161. if (this.cameraColorCurves) {
  61162. this._defines.CAMERACOLORCURVES = true;
  61163. }
  61164. if (this.overloadedShadeIntensity != 1 ||
  61165. this.overloadedShadowIntensity != 1) {
  61166. this._defines.OVERLOADEDSHADOWVALUES = true;
  61167. }
  61168. if (this.overloadedMicroSurfaceIntensity > 0 ||
  61169. this.overloadedEmissiveIntensity > 0 ||
  61170. this.overloadedReflectivityIntensity > 0 ||
  61171. this.overloadedAlbedoIntensity > 0 ||
  61172. this.overloadedAmbientIntensity > 0 ||
  61173. this.overloadedReflectionIntensity > 0) {
  61174. this._defines.OVERLOADEDVALUES = true;
  61175. }
  61176. // Point size
  61177. if (this.pointsCloud || scene.forcePointsCloud) {
  61178. this._defines.POINTSIZE = true;
  61179. }
  61180. // Fog
  61181. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  61182. this._defines.FOG = true;
  61183. }
  61184. if (scene.lightsEnabled && !this.disableLighting) {
  61185. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  61186. }
  61187. if (BABYLON.StandardMaterial.FresnelEnabled) {
  61188. // Fresnel
  61189. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  61190. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61191. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  61192. this._defines.OPACITYFRESNEL = true;
  61193. }
  61194. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61195. this._defines.EMISSIVEFRESNEL = true;
  61196. }
  61197. needNormals = true;
  61198. this._defines.FRESNEL = true;
  61199. }
  61200. }
  61201. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  61202. this._defines.SPECULAROVERALPHA = true;
  61203. }
  61204. if (this.usePhysicalLightFalloff) {
  61205. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  61206. }
  61207. if (this.useRadianceOverAlpha) {
  61208. this._defines.RADIANCEOVERALPHA = true;
  61209. }
  61210. // Attribs
  61211. if (mesh) {
  61212. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61213. this._defines.NORMAL = true;
  61214. }
  61215. if (needUVs) {
  61216. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61217. this._defines.UV1 = true;
  61218. }
  61219. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61220. this._defines.UV2 = true;
  61221. }
  61222. }
  61223. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  61224. this._defines.VERTEXCOLOR = true;
  61225. if (mesh.hasVertexAlpha) {
  61226. this._defines.VERTEXALPHA = true;
  61227. }
  61228. }
  61229. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61230. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  61231. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  61232. }
  61233. // Instances
  61234. if (useInstances) {
  61235. this._defines.INSTANCES = true;
  61236. }
  61237. }
  61238. // Get correct effect
  61239. if (!this._defines.isEqual(this._cachedDefines)) {
  61240. this._defines.cloneTo(this._cachedDefines);
  61241. scene.resetCachedMaterial();
  61242. // Fallbacks
  61243. var fallbacks = new BABYLON.EffectFallbacks();
  61244. if (this._defines.REFLECTION) {
  61245. fallbacks.addFallback(0, "REFLECTION");
  61246. }
  61247. if (this._defines.REFRACTION) {
  61248. fallbacks.addFallback(0, "REFRACTION");
  61249. }
  61250. if (this._defines.REFLECTIVITY) {
  61251. fallbacks.addFallback(0, "REFLECTIVITY");
  61252. }
  61253. if (this._defines.BUMP) {
  61254. fallbacks.addFallback(0, "BUMP");
  61255. }
  61256. if (this._defines.PARALLAX) {
  61257. fallbacks.addFallback(1, "PARALLAX");
  61258. }
  61259. if (this._defines.PARALLAXOCCLUSION) {
  61260. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  61261. }
  61262. if (this._defines.SPECULAROVERALPHA) {
  61263. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  61264. }
  61265. if (this._defines.FOG) {
  61266. fallbacks.addFallback(1, "FOG");
  61267. }
  61268. if (this._defines.POINTSIZE) {
  61269. fallbacks.addFallback(0, "POINTSIZE");
  61270. }
  61271. if (this._defines.LOGARITHMICDEPTH) {
  61272. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  61273. }
  61274. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  61275. if (this._defines.SPECULARTERM) {
  61276. fallbacks.addFallback(0, "SPECULARTERM");
  61277. }
  61278. if (this._defines.OPACITYFRESNEL) {
  61279. fallbacks.addFallback(1, "OPACITYFRESNEL");
  61280. }
  61281. if (this._defines.EMISSIVEFRESNEL) {
  61282. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  61283. }
  61284. if (this._defines.FRESNEL) {
  61285. fallbacks.addFallback(3, "FRESNEL");
  61286. }
  61287. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  61288. fallbacks.addCPUSkinningFallback(0, mesh);
  61289. }
  61290. //Attributes
  61291. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61292. if (this._defines.NORMAL) {
  61293. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61294. }
  61295. if (this._defines.UV1) {
  61296. attribs.push(BABYLON.VertexBuffer.UVKind);
  61297. }
  61298. if (this._defines.UV2) {
  61299. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61300. }
  61301. if (this._defines.VERTEXCOLOR) {
  61302. attribs.push(BABYLON.VertexBuffer.ColorKind);
  61303. }
  61304. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  61305. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  61306. // Legacy browser patch
  61307. var shaderName = "pbr";
  61308. if (!scene.getEngine().getCaps().standardDerivatives) {
  61309. shaderName = "legacypbr";
  61310. }
  61311. var join = this._defines.toString();
  61312. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  61313. "vFogInfos", "vFogColor", "pointSize",
  61314. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  61315. "mBones",
  61316. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  61317. "depthValues",
  61318. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  61319. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  61320. "logarithmicDepthConstant",
  61321. "vSphericalX", "vSphericalY", "vSphericalZ",
  61322. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  61323. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  61324. "vMicrosurfaceTextureLods",
  61325. "vCameraInfos"
  61326. ];
  61327. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  61328. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  61329. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  61330. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  61331. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  61332. }
  61333. if (!this._effect.isReady()) {
  61334. return false;
  61335. }
  61336. this._renderId = scene.getRenderId();
  61337. this._wasPreviouslyReady = true;
  61338. if (mesh) {
  61339. if (!mesh._materialDefines) {
  61340. mesh._materialDefines = new PBRMaterialDefines();
  61341. }
  61342. this._defines.cloneTo(mesh._materialDefines);
  61343. }
  61344. return true;
  61345. };
  61346. PBRMaterial.prototype.unbind = function () {
  61347. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  61348. this._effect.setTexture("reflection2DSampler", null);
  61349. }
  61350. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  61351. this._effect.setTexture("refraction2DSampler", null);
  61352. }
  61353. _super.prototype.unbind.call(this);
  61354. };
  61355. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  61356. this._effect.setMatrix("world", world);
  61357. };
  61358. PBRMaterial.prototype.bind = function (world, mesh) {
  61359. this._myScene = this.getScene();
  61360. // Matrices
  61361. this.bindOnlyWorldMatrix(world);
  61362. // Bones
  61363. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  61364. if (this._myScene.getCachedMaterial() !== this) {
  61365. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  61366. if (BABYLON.StandardMaterial.FresnelEnabled) {
  61367. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  61368. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  61369. }
  61370. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  61371. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  61372. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  61373. }
  61374. }
  61375. // Textures
  61376. if (this._myScene.texturesEnabled) {
  61377. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  61378. this._effect.setTexture("albedoSampler", this.albedoTexture);
  61379. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  61380. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  61381. }
  61382. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  61383. this._effect.setTexture("ambientSampler", this.ambientTexture);
  61384. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  61385. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  61386. }
  61387. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  61388. this._effect.setTexture("opacitySampler", this.opacityTexture);
  61389. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  61390. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  61391. }
  61392. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  61393. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  61394. if (this.reflectionTexture.isCube) {
  61395. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  61396. }
  61397. else {
  61398. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  61399. }
  61400. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  61401. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  61402. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  61403. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  61404. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  61405. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  61406. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  61407. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  61408. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  61409. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  61410. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  61411. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  61412. }
  61413. }
  61414. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  61415. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  61416. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  61417. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  61418. }
  61419. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  61420. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  61421. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  61422. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  61423. }
  61424. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  61425. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  61426. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  61427. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  61428. }
  61429. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  61430. this._effect.setTexture("bumpSampler", this.bumpTexture);
  61431. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  61432. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  61433. }
  61434. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  61435. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  61436. var depth = 1.0;
  61437. if (this.refractionTexture.isCube) {
  61438. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  61439. }
  61440. else {
  61441. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  61442. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  61443. if (this.refractionTexture.depth) {
  61444. depth = this.refractionTexture.depth;
  61445. }
  61446. }
  61447. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  61448. }
  61449. if ((this.reflectionTexture || this.refractionTexture)) {
  61450. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  61451. }
  61452. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  61453. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  61454. }
  61455. }
  61456. // Clip plane
  61457. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  61458. // Point size
  61459. if (this.pointsCloud) {
  61460. this._effect.setFloat("pointSize", this.pointSize);
  61461. }
  61462. // Colors
  61463. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  61464. // GAMMA CORRECTION.
  61465. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  61466. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  61467. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  61468. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  61469. // GAMMA CORRECTION.
  61470. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  61471. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  61472. // GAMMA CORRECTION.
  61473. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  61474. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  61475. }
  61476. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  61477. // GAMMA CORRECTION.
  61478. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  61479. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  61480. // Lights
  61481. if (this._myScene.lightsEnabled && !this.disableLighting) {
  61482. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  61483. }
  61484. // View
  61485. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  61486. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  61487. }
  61488. // Fog
  61489. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  61490. this._lightingInfos.x = this.directIntensity;
  61491. this._lightingInfos.y = this.emissiveIntensity;
  61492. this._lightingInfos.z = this.environmentIntensity;
  61493. this._lightingInfos.w = this.specularIntensity;
  61494. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  61495. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  61496. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  61497. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  61498. this._cameraInfos.x = this.cameraExposure;
  61499. this._cameraInfos.y = this.cameraContrast;
  61500. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  61501. if (this.cameraColorCurves) {
  61502. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  61503. }
  61504. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  61505. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  61506. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  61507. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  61508. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  61509. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  61510. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  61511. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  61512. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  61513. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  61514. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  61515. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  61516. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  61517. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  61518. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  61519. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  61520. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  61521. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  61522. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  61523. // Log. depth
  61524. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  61525. }
  61526. _super.prototype.bind.call(this, world, mesh);
  61527. this._myScene = null;
  61528. };
  61529. PBRMaterial.prototype.getAnimatables = function () {
  61530. var results = [];
  61531. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  61532. results.push(this.albedoTexture);
  61533. }
  61534. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  61535. results.push(this.ambientTexture);
  61536. }
  61537. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  61538. results.push(this.opacityTexture);
  61539. }
  61540. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  61541. results.push(this.reflectionTexture);
  61542. }
  61543. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  61544. results.push(this.emissiveTexture);
  61545. }
  61546. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  61547. results.push(this.reflectivityTexture);
  61548. }
  61549. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  61550. results.push(this.bumpTexture);
  61551. }
  61552. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  61553. results.push(this.lightmapTexture);
  61554. }
  61555. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  61556. results.push(this.refractionTexture);
  61557. }
  61558. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  61559. results.push(this.cameraColorGradingTexture);
  61560. }
  61561. return results;
  61562. };
  61563. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  61564. if (forceDisposeTextures) {
  61565. if (this.albedoTexture) {
  61566. this.albedoTexture.dispose();
  61567. }
  61568. if (this.ambientTexture) {
  61569. this.ambientTexture.dispose();
  61570. }
  61571. if (this.opacityTexture) {
  61572. this.opacityTexture.dispose();
  61573. }
  61574. if (this.reflectionTexture) {
  61575. this.reflectionTexture.dispose();
  61576. }
  61577. if (this.emissiveTexture) {
  61578. this.emissiveTexture.dispose();
  61579. }
  61580. if (this.reflectivityTexture) {
  61581. this.reflectivityTexture.dispose();
  61582. }
  61583. if (this.bumpTexture) {
  61584. this.bumpTexture.dispose();
  61585. }
  61586. if (this.lightmapTexture) {
  61587. this.lightmapTexture.dispose();
  61588. }
  61589. if (this.refractionTexture) {
  61590. this.refractionTexture.dispose();
  61591. }
  61592. if (this.cameraColorGradingTexture) {
  61593. this.cameraColorGradingTexture.dispose();
  61594. }
  61595. }
  61596. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  61597. };
  61598. PBRMaterial.prototype.clone = function (name) {
  61599. var _this = this;
  61600. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  61601. };
  61602. PBRMaterial.prototype.serialize = function () {
  61603. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  61604. serializationObject.customType = "BABYLON.PBRMaterial";
  61605. return serializationObject;
  61606. };
  61607. // Statics
  61608. PBRMaterial.Parse = function (source, scene, rootUrl) {
  61609. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  61610. };
  61611. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  61612. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  61613. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  61614. PBRMaterial._scaledReflection = new BABYLON.Color3();
  61615. __decorate([
  61616. BABYLON.serialize()
  61617. ], PBRMaterial.prototype, "directIntensity", void 0);
  61618. __decorate([
  61619. BABYLON.serialize()
  61620. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  61621. __decorate([
  61622. BABYLON.serialize()
  61623. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  61624. __decorate([
  61625. BABYLON.serialize()
  61626. ], PBRMaterial.prototype, "specularIntensity", void 0);
  61627. __decorate([
  61628. BABYLON.serialize()
  61629. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  61630. __decorate([
  61631. BABYLON.serialize()
  61632. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  61633. __decorate([
  61634. BABYLON.serialize()
  61635. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  61636. __decorate([
  61637. BABYLON.serialize()
  61638. ], PBRMaterial.prototype, "cameraExposure", void 0);
  61639. __decorate([
  61640. BABYLON.serialize()
  61641. ], PBRMaterial.prototype, "cameraContrast", void 0);
  61642. __decorate([
  61643. BABYLON.serializeAsTexture()
  61644. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  61645. __decorate([
  61646. BABYLON.serializeAsColorCurves()
  61647. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  61648. __decorate([
  61649. BABYLON.serializeAsColor3()
  61650. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  61651. __decorate([
  61652. BABYLON.serialize()
  61653. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  61654. __decorate([
  61655. BABYLON.serializeAsColor3()
  61656. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  61657. __decorate([
  61658. BABYLON.serialize()
  61659. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  61660. __decorate([
  61661. BABYLON.serializeAsColor3()
  61662. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  61663. __decorate([
  61664. BABYLON.serialize()
  61665. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  61666. __decorate([
  61667. BABYLON.serializeAsColor3()
  61668. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  61669. __decorate([
  61670. BABYLON.serialize()
  61671. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  61672. __decorate([
  61673. BABYLON.serializeAsColor3()
  61674. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  61675. __decorate([
  61676. BABYLON.serialize()
  61677. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  61678. __decorate([
  61679. BABYLON.serialize()
  61680. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  61681. __decorate([
  61682. BABYLON.serialize()
  61683. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  61684. __decorate([
  61685. BABYLON.serializeAsTexture()
  61686. ], PBRMaterial.prototype, "albedoTexture", void 0);
  61687. __decorate([
  61688. BABYLON.serializeAsTexture()
  61689. ], PBRMaterial.prototype, "ambientTexture", void 0);
  61690. __decorate([
  61691. BABYLON.serializeAsTexture()
  61692. ], PBRMaterial.prototype, "opacityTexture", void 0);
  61693. __decorate([
  61694. BABYLON.serializeAsTexture()
  61695. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  61696. __decorate([
  61697. BABYLON.serializeAsTexture()
  61698. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  61699. __decorate([
  61700. BABYLON.serializeAsTexture()
  61701. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  61702. __decorate([
  61703. BABYLON.serializeAsTexture()
  61704. ], PBRMaterial.prototype, "bumpTexture", void 0);
  61705. __decorate([
  61706. BABYLON.serializeAsTexture()
  61707. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  61708. __decorate([
  61709. BABYLON.serializeAsTexture()
  61710. ], PBRMaterial.prototype, "refractionTexture", void 0);
  61711. __decorate([
  61712. BABYLON.serializeAsColor3("ambient")
  61713. ], PBRMaterial.prototype, "ambientColor", void 0);
  61714. __decorate([
  61715. BABYLON.serializeAsColor3("albedo")
  61716. ], PBRMaterial.prototype, "albedoColor", void 0);
  61717. __decorate([
  61718. BABYLON.serializeAsColor3("reflectivity")
  61719. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  61720. __decorate([
  61721. BABYLON.serializeAsColor3("reflection")
  61722. ], PBRMaterial.prototype, "reflectionColor", void 0);
  61723. __decorate([
  61724. BABYLON.serializeAsColor3("emissive")
  61725. ], PBRMaterial.prototype, "emissiveColor", void 0);
  61726. __decorate([
  61727. BABYLON.serialize()
  61728. ], PBRMaterial.prototype, "microSurface", void 0);
  61729. __decorate([
  61730. BABYLON.serialize()
  61731. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  61732. __decorate([
  61733. BABYLON.serialize()
  61734. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  61735. __decorate([
  61736. BABYLON.serializeAsFresnelParameters()
  61737. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  61738. __decorate([
  61739. BABYLON.serializeAsFresnelParameters()
  61740. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  61741. __decorate([
  61742. BABYLON.serialize()
  61743. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  61744. __decorate([
  61745. BABYLON.serialize()
  61746. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  61747. __decorate([
  61748. BABYLON.serialize()
  61749. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  61750. __decorate([
  61751. BABYLON.serialize()
  61752. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  61753. __decorate([
  61754. BABYLON.serialize()
  61755. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  61756. __decorate([
  61757. BABYLON.serialize()
  61758. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  61759. __decorate([
  61760. BABYLON.serialize()
  61761. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  61762. __decorate([
  61763. BABYLON.serialize()
  61764. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  61765. __decorate([
  61766. BABYLON.serialize()
  61767. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  61768. __decorate([
  61769. BABYLON.serialize()
  61770. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  61771. __decorate([
  61772. BABYLON.serialize()
  61773. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  61774. __decorate([
  61775. BABYLON.serialize()
  61776. ], PBRMaterial.prototype, "useParallax", void 0);
  61777. __decorate([
  61778. BABYLON.serialize()
  61779. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  61780. __decorate([
  61781. BABYLON.serialize()
  61782. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  61783. __decorate([
  61784. BABYLON.serialize()
  61785. ], PBRMaterial.prototype, "disableLighting", void 0);
  61786. __decorate([
  61787. BABYLON.serialize()
  61788. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  61789. __decorate([
  61790. BABYLON.serialize()
  61791. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  61792. __decorate([
  61793. BABYLON.serialize()
  61794. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  61795. __decorate([
  61796. BABYLON.serialize()
  61797. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  61798. return PBRMaterial;
  61799. }(BABYLON.Material));
  61800. BABYLON.PBRMaterial = PBRMaterial;
  61801. })(BABYLON || (BABYLON = {}));
  61802. var BABYLON;
  61803. (function (BABYLON) {
  61804. var StandardRenderingPipeline = (function (_super) {
  61805. __extends(StandardRenderingPipeline, _super);
  61806. /**
  61807. * @constructor
  61808. * @param {string} name - The rendering pipeline name
  61809. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  61810. * @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)
  61811. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  61812. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  61813. */
  61814. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  61815. var _this = this;
  61816. if (originalPostProcess === void 0) { originalPostProcess = null; }
  61817. _super.call(this, scene.getEngine(), name);
  61818. this.downSampleX4PostProcess = null;
  61819. this.brightPassPostProcess = null;
  61820. this.gaussianBlurHPostProcesses = [];
  61821. this.gaussianBlurVPostProcesses = [];
  61822. this.textureAdderPostProcess = null;
  61823. this.depthOfFieldSourcePostProcess = null;
  61824. this.depthOfFieldPostProcess = null;
  61825. this.brightThreshold = 1.0;
  61826. this.gaussianCoefficient = 0.25;
  61827. this.gaussianMean = 1.0;
  61828. this.gaussianStandardDeviation = 1.0;
  61829. this.exposure = 1.0;
  61830. this.lensTexture = null;
  61831. this.depthOfFieldDistance = 10.0;
  61832. this._depthRenderer = null;
  61833. // Getters and setters
  61834. this._blurEnabled = true;
  61835. this._depthOfFieldEnabled = false;
  61836. // Initialize
  61837. this._scene = scene;
  61838. // Create pass post-processe
  61839. if (!originalPostProcess) {
  61840. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  61841. }
  61842. else {
  61843. this.originalPostProcess = originalPostProcess;
  61844. }
  61845. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  61846. // Create down sample X4 post-process
  61847. this._createDownSampleX4PostProcess(scene, ratio / 2);
  61848. // Create bright pass post-process
  61849. this._createBrightPassPostProcess(scene, ratio / 2);
  61850. // Create gaussian blur post-processes (down sampling blurs)
  61851. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  61852. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  61853. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  61854. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  61855. // Create texture adder post-process
  61856. this._createTextureAdderPostProcess(scene, ratio);
  61857. // Create depth-of-field source post-process
  61858. this.depthOfFieldSourcePostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61859. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.depthOfFieldSourcePostProcess; }, true));
  61860. // Create gaussian blur used by depth-of-field
  61861. this._createGaussianBlurPostProcesses(scene, ratio / 2, 4);
  61862. // Create depth-of-field post-process
  61863. this._createDepthOfFieldPostProcess(scene, ratio);
  61864. // Finish
  61865. scene.postProcessRenderPipelineManager.addPipeline(this);
  61866. if (cameras !== null) {
  61867. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  61868. }
  61869. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfFieldSource", cameras);
  61870. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH4", cameras);
  61871. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV4", cameras);
  61872. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", cameras);
  61873. }
  61874. Object.defineProperty(StandardRenderingPipeline.prototype, "BlurEnabled", {
  61875. get: function () {
  61876. return this._blurEnabled;
  61877. },
  61878. set: function (enabled) {
  61879. if (enabled && !this._blurEnabled || !enabled && this._blurEnabled) {
  61880. for (var i = 0; i < this.gaussianBlurHPostProcesses.length - 1; i++) {
  61881. if (enabled) {
  61882. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._scene.cameras);
  61883. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._scene.cameras);
  61884. }
  61885. else {
  61886. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + i, this._scene.cameras);
  61887. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + i, this._scene.cameras);
  61888. }
  61889. }
  61890. }
  61891. this._blurEnabled = enabled;
  61892. },
  61893. enumerable: true,
  61894. configurable: true
  61895. });
  61896. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  61897. get: function () {
  61898. return this._depthOfFieldEnabled;
  61899. },
  61900. set: function (enabled) {
  61901. if (enabled && !this._depthOfFieldEnabled) {
  61902. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfFieldSource", this._scene.cameras);
  61903. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH4", this._scene.cameras);
  61904. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV4", this._scene.cameras);
  61905. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  61906. this._depthRenderer = this._scene.enableDepthRenderer();
  61907. }
  61908. else if (!enabled && this._depthOfFieldEnabled) {
  61909. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfFieldSource", this._scene.cameras);
  61910. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH4", this._scene.cameras);
  61911. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV4", this._scene.cameras);
  61912. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  61913. }
  61914. this._depthOfFieldEnabled = enabled;
  61915. },
  61916. enumerable: true,
  61917. configurable: true
  61918. });
  61919. // Down Sample X4 Post-Processs
  61920. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  61921. var _this = this;
  61922. var downSampleX4Offsets = new Array(32);
  61923. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61924. this.downSampleX4PostProcess.onApply = function (effect) {
  61925. var id = 0;
  61926. for (var i = -2; i < 2; i++) {
  61927. for (var j = -2; j < 2; j++) {
  61928. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  61929. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  61930. id += 2;
  61931. }
  61932. }
  61933. effect.setArray2("dsOffsets", downSampleX4Offsets);
  61934. };
  61935. // Add to pipeline
  61936. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  61937. };
  61938. // Brightpass Post-Process
  61939. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  61940. var _this = this;
  61941. var brightOffsets = new Array(8);
  61942. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61943. this.brightPassPostProcess.onApply = function (effect) {
  61944. var sU = (1.0 / _this.brightPassPostProcess.width);
  61945. var sV = (1.0 / _this.brightPassPostProcess.height);
  61946. brightOffsets[0] = -0.5 * sU;
  61947. brightOffsets[1] = 0.5 * sV;
  61948. brightOffsets[2] = 0.5 * sU;
  61949. brightOffsets[3] = 0.5 * sV;
  61950. brightOffsets[4] = -0.5 * sU;
  61951. brightOffsets[5] = -0.5 * sV;
  61952. brightOffsets[6] = 0.5 * sU;
  61953. brightOffsets[7] = -0.5 * sV;
  61954. effect.setArray2("dsOffsets", brightOffsets);
  61955. effect.setFloat("brightThreshold", _this.brightThreshold);
  61956. };
  61957. // Add to pipeline
  61958. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  61959. };
  61960. // Create gaussian blur H&V post-processes
  61961. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  61962. var _this = this;
  61963. var blurOffsets = new Array(9);
  61964. var blurWeights = new Array(9);
  61965. var uniforms = ["blurOffsets", "blurWeights"];
  61966. var callback = function (height) {
  61967. return function (effect) {
  61968. // Weights
  61969. var x = 0.0;
  61970. for (var i = 0; i < 9; i++) {
  61971. x = (i - 4.0) / 4.0;
  61972. blurWeights[i] =
  61973. _this.gaussianCoefficient
  61974. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  61975. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  61976. }
  61977. var lastOutputDimensions = {
  61978. width: scene.getEngine().getRenderWidth(),
  61979. height: scene.getEngine().getRenderHeight()
  61980. };
  61981. for (var i = 0; i < 9; i++) {
  61982. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  61983. blurOffsets[i] = value;
  61984. }
  61985. effect.setArray("blurOffsets", blurOffsets);
  61986. effect.setArray("blurWeights", blurWeights);
  61987. };
  61988. };
  61989. // Create horizontal gaussian blur post-processes
  61990. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61991. gaussianBlurHPostProcess.onApply = callback(false);
  61992. // Create vertical gaussian blur post-process
  61993. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  61994. gaussianBlurVPostProcess.onApply = callback(true);
  61995. // Add to pipeline
  61996. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  61997. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  61998. // Finish
  61999. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  62000. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  62001. };
  62002. // Create texture adder post-process
  62003. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  62004. var _this = this;
  62005. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  62006. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62007. this.textureAdderPostProcess.onApply = function (effect) {
  62008. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  62009. effect.setTexture("lensSampler", _this.lensTexture);
  62010. effect.setFloat("exposure", _this.exposure);
  62011. };
  62012. // Add to pipeline
  62013. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  62014. };
  62015. // Create depth-of-field post-process
  62016. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  62017. var _this = this;
  62018. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  62019. this.depthOfFieldPostProcess.onApply = function (effect) {
  62020. effect.setTextureFromPostProcess("otherSampler", _this.depthOfFieldSourcePostProcess);
  62021. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  62022. effect.setFloat("distance", _this.depthOfFieldDistance);
  62023. };
  62024. // Add to pipeline
  62025. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  62026. };
  62027. return StandardRenderingPipeline;
  62028. }(BABYLON.PostProcessRenderPipeline));
  62029. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  62030. })(BABYLON || (BABYLON = {}));
  62031. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#ifdef DIFFUSE\nvec2 diffuseUV=vDiffuseUV;\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,diffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","ellipse2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","ellipse2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat ms=properties.z;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<ms) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=ms;\n}\nfloat angle=TWOPI*segi/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat ms=properties.z;\nfloat angle=TWOPI*(index-1.0)/ms;\npos2.x=(cos(angle)/2.0)+0.5;\npos2.y=(sin(angle)/2.0)+0.5;\n}\n#endif\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","legacydefaultPixelShader":"#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..3]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef REFLECTION\nvarying vec3 vReflectionUVW;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\nuniform vec2 vReflectionInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 normalW=normalize(vNormalW);\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\nfloat glossiness=0.;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\nglossiness=vSpecularColor.a;\n#endif\nfloat shadow=1.;\n#include<lightFragment>[0..3]\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha=vDiffuseColor.a;\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor=texture2D(specularSampler,vSpecularUV).rgb*vSpecularInfos.y;\n#endif\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor,alpha);\n#include<fogFragment>\ngl_FragColor=color;\n}","legacydefaultVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTION\nuniform vec3 vEyePosition;\nvarying vec3 vReflectionUVW;\nuniform mat4 reflectionMatrix;\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 coords=vec3(view*vec4(worldNormal,0.0));\nreturn vec3(reflectionMatrix*vec4(coords,1.0));\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn position;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef REFLECTION\nvReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),vNormalW);\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","legacypbrPixelShader":"precision mediump float;\n\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vAlbedoColor;\nuniform vec3 vReflectionColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n#include<clipPlaneFragmentDeclaration>\n#ifdef CAMERACOLORGRADING\nuniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;\n#endif\n\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution= vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0);\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance,alpha);\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor,cameraColorGrading2DSampler,vCameraColorGradingInfos,vCameraColorGradingScaleOffset);\n#endif\ngl_FragColor=finalColor;\n}","legacypbrVertexShader":"precision mediump float;\n\nattribute vec3 position;\nattribute vec3 normal;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 world;\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","lines2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","lines2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute vec2 position;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec2 boundingMin;\natt vec2 boundingMax;\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4((position.xy-boundingMin)/(boundingMax-boundingMin),1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=position.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV).rgb*vAmbientInfos.y;\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV).rgb*vLightmapInfos.y;\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY)\nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY)\nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","rect2dPixelShader":"varying vec4 vColor;\nvoid main(void) {\ngl_FragColor=vColor;\n}","rect2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n#ifdef Border\natt float borderThickness;\n#endif\n#ifdef FillSolid\natt vec4 fillSolidColor;\n#endif\n#ifdef BorderSolid\natt vec4 borderSolidColor;\n#endif\n#ifdef FillGradient\natt vec4 fillGradientColor1;\natt vec4 fillGradientColor2;\natt vec4 fillGradientTY;\n#endif\n#ifdef BorderGradient\natt vec4 borderGradientColor1;\natt vec4 borderGradientColor2;\natt vec4 borderGradientTY;\n#endif\n\natt vec3 properties;\n\n#define rsub0 17.0\n#define rsub1 33.0\n#define rsub2 49.0\n#define rsub3 65.0\n#define rsub 64.0\n#define TWOPI 6.28318530\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (properties.z == 0.0) {\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<4.0) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=4.0;\n}\nif (segi == 0.0) {\npos2=vec2(1.0,1.0);\n} \nelse if (segi == 1.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (segi == 2.0) {\npos2=vec2(0.0,0.0);\n} \nelse {\npos2=vec2(0.0,1.0);\n}\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse if (index == 1.0) {\npos2=vec2(1.0,1.0);\n}\nelse if (index == 2.0) {\npos2=vec2(1.0,0.0);\n}\nelse if (index == 3.0) {\npos2=vec2(0.0,0.0);\n}\nelse {\npos2=vec2(0.0,1.0);\n}\n#endif\n}\nelse\n{\n#ifdef Border\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\nvec2 borderOffset=vec2(1.0,1.0);\nfloat segi=index;\nif (index<rsub) {\nborderOffset=vec2(1.0-(borderThickness*2.0/w),1.0-(borderThickness*2.0/h));\n}\nelse {\nsegi-=rsub;\n}\n\nif (segi<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (segi<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (segi<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\npos2.x=((pos2.x-0.5)*borderOffset.x)+0.5;\npos2.y=((pos2.y-0.5)*borderOffset.y)+0.5;\n#else\nif (index == 0.0) {\npos2=vec2(0.5,0.5);\n}\nelse {\nfloat w=properties.x;\nfloat h=properties.y;\nfloat r=properties.z;\nfloat nru=r/w;\nfloat nrv=r/h;\n\nif (index<rsub0) {\npos2=vec2(1.0-nru,nrv);\n}\n\nelse if (index<rsub1) {\npos2=vec2(nru,nrv);\n}\n\nelse if (index<rsub2) {\npos2=vec2(nru,1.0-nrv);\n}\n\nelse {\npos2=vec2(1.0-nru,1.0-nrv);\n}\nfloat angle=TWOPI-((index-1.0)*TWOPI/(rsub-0.5));\npos2.x+=cos(angle)*nru;\npos2.y+=sin(angle)*nrv;\n}\n#endif\n}\n#ifdef FillSolid\nvColor=fillSolidColor;\n#endif\n#ifdef BorderSolid\nvColor=borderSolidColor;\n#endif\n#ifdef FillGradient\nfloat v=dot(vec4(pos2.xy,1,1),fillGradientTY);\nvColor=mix(fillGradientColor2,fillGradientColor1,v); \n#endif\n#ifdef BorderGradient\nfloat v=dot(vec4(pos2.xy,1,1),borderGradientTY);\nvColor=mix(borderGradientColor2,borderGradientColor1,v); \n#endif\nvColor.a*=opacity;\nvec4 pos;\npos.xy=pos2.xy*properties.xy;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","sprite2dPixelShader":"varying vec2 vUV;\nvarying float vOpacity;\nuniform bool alphaTest;\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest)\n{\nif (color.a<0.95) {\ndiscard;\n}\n}\ncolor.a*=vOpacity;\ngl_FragColor=color;\n}","sprite2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 scaleFactor;\natt vec2 textureSize;\n\natt vec3 properties;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\n\n\nvarying vec2 vUV;\nvarying float vOpacity;\nvoid main(void) {\nvec2 pos2;\n\nvec2 off=vec2(0.0,0.0);\nvec2 sfSizeUV=sizeUV*scaleFactor;\nfloat frame=properties.x;\nfloat invertY=properties.y;\nfloat alignToPixel=properties.z;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,topLeftUV.y-off.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x+(frame*sfSizeUV.x)+off.x,(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 2.0) {\npos2=vec2( 1.0,1.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),(topLeftUV.y+sfSizeUV.y));\n}\n\nelse if (index == 3.0) {\npos2=vec2( 1.0,0.0);\nvUV=vec2(topLeftUV.x+sfSizeUV.x+(frame*sfSizeUV.x),topLeftUV.y-off.y);\n}\nif (invertY == 1.0) {\nvUV.y=1.0-vUV.y;\n}\nvec4 pos;\nif (alignToPixel == 1.0)\n{\npos.xy=floor(pos2.xy*sizeUV*textureSize);\n} else {\npos.xy=pos2.xy*sizeUV*textureSize;\n}\nvOpacity=opacity;\npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\n} ","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nfFogDistance=viewPos.z;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*2.0,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*2.0))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\ngl_FragColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","text2dPixelShader":"varying vec4 vColor;\nvarying vec2 vUV;\n\nuniform sampler2D diffuseSampler;\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\ngl_FragColor=color*vColor;\n}","text2dVertexShader":"\n#ifdef Instanced\n#define att attribute\n#else\n#define att uniform\n#endif\n\nattribute float index;\natt vec2 zBias;\natt vec4 transformX;\natt vec4 transformY;\natt float opacity;\natt vec2 topLeftUV;\natt vec2 sizeUV;\natt vec2 textureSize;\natt vec4 color;\natt float superSampleFactor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\nvoid main(void) {\nvec2 pos2;\n\nif (index == 0.0) {\npos2=vec2(0.0,0.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y+sizeUV.y);\n}\n\nelse if (index == 1.0) {\npos2=vec2(0.0,1.0);\nvUV=vec2(topLeftUV.x,topLeftUV.y);\n}\n\nelse if (index == 2.0) {\npos2=vec2(1.0,1.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y);\n}\n\nelse if (index == 3.0) {\npos2=vec2(1.0,0.0);\nvUV=vec2(topLeftUV.x+sizeUV.x,topLeftUV.y+sizeUV.y);\n}\n\nvUV=(floor(vUV*textureSize)+vec2(0.0,0.0))/textureSize;\nvColor=color;\nvColor.a*=opacity;\nvec4 pos;\npos.xy=floor(pos2.xy*superSampleFactor*sizeUV*textureSize); \npos.z=1.0;\npos.w=1.0;\ngl_Position=vec4(dot(pos,transformX),dot(pos,transformY),zBias.x,1);\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}"};
  62032. BABYLON.Effect.IncludesShadersStore={"bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpFragment":"#ifdef BUMP\nvec2 bumpUV=vBumpUV;\n#endif\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,bumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nvec2 uvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,bumpUV,vBumpInfos.z);\n#else\nvec2 uvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\ndiffuseUV+=uvOffset;\nbumpUV+=uvOffset;\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,bumpUV);\n#endif","bumpFragmentFunctions":"#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 binormal=dp2perp*duv1.y+dp1perp*duv2.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(vec3 viewDir,mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\nmap=map*255./127.-128./127.;\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fFogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fFogDistance*fFogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nfFogDistance=(view*worldPos).z;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying float fFogDistance;\n#endif","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\n}\n#endif","helperFunctions":"mat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","lightFragment":"#ifdef LIGHT{X}\n#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,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#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\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvec3 direction=normalize(vDirectionW);\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\nfloat biasedDepth=depth-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadow(vec4 vPositionFromLight,sampler2D shadowSampler,float darkness,float bias)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,sampler2D shadowSampler,float mapSize,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\nfloat biasedDepth=depth.z-bias;\n#ifndef SHADOWFULLFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<biasedDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<biasedDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\nfloat linstep(float low,float high,float v) {\nreturn clamp((v-low)/(high-low),0.0,1.0);\n}\nfloat ChebychevInequality(vec2 moments,float compare,float bias)\n{\nfloat p=smoothstep(compare-bias,compare,moments.x);\nfloat variance=max(moments.y-moments.x*moments.x,0.02);\nfloat d=compare-moments.x;\nfloat p_max=linstep(0.2,1.0,variance/(variance+d*d));\nreturn clamp(max(p,p_max),0.0,1.0);\n}\nfloat computeShadowWithVSM(vec4 vPositionFromLight,sampler2D shadowSampler,float bias,float darkness)\n{\nvec3 depth=vPositionFromLight.xyz/vPositionFromLight.w;\ndepth=0.5*depth+vec3(0.5);\nvec2 uv=depth.xy;\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0 || depth.z>=1.0)\n{\nreturn 1.0;\n}\nvec4 texel=texture2D(shadowSampler,uv);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  62033. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,n){void 0===n&&(n=1.401298e-45);var r=t-i;return-n<=r&&r<=n},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,n){return void 0===i&&(i=0),void 0===n&&(n=1),Math.min(n,Math.max(i,t))},t}();t.MathTools=i;var n=function(){function n(t,i,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),this.r=t,this.g=i,this.b=n}return n.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},n.prototype.getClassName=function(){return\"Color3\"},n.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},n.prototype.toColor4=function(t){return void 0===t&&(t=1),new r(this.r,this.g,this.b,t)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},n.prototype.multiply=function(t){return new n(this.r*t.r,this.g*t.g,this.b*t.b)},n.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},n.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},n.prototype.equalsFloats=function(t,i,n){return this.r===t&&this.g===i&&this.b===n},n.prototype.scale=function(t){return new n(this.r*t,this.g*t,this.b*t)},n.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},n.prototype.add=function(t){return new n(this.r+t.r,this.g+t.g,this.b+t.b)},n.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},n.prototype.subtract=function(t){return new n(this.r-t.r,this.g-t.g,this.b-t.b)},n.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},n.prototype.clone=function(){return new n(this.r,this.g,this.b)},n.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},n.prototype.copyFromFloats=function(t,i,n){return this.r=t,this.g=i,this.b=n,this},n.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)},n.prototype.toLinearSpace=function(){var t=new n;return this.toLinearSpaceToRef(t),t},n.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},n.prototype.toGammaSpace=function(){var t=new n;return this.toGammaSpaceToRef(t),t},n.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},n.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new n(0,0,0);var i=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return n.FromInts(i,r,o)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1],t[i+2])},n.FromInts=function(t,i,r){return new n(t/255,i/255,r/255)},n.Lerp=function(t,i,r){var o=t.r+(i.r-t.r)*r,e=t.g+(i.g-t.g)*r,s=t.b+(i.b-t.b)*r;return new n(o,e,s)},n.Red=function(){return new n(1,0,0)},n.Green=function(){return new n(0,1,0)},n.Blue=function(){return new n(0,0,1)},n.Black=function(){return new n(0,0,0)},n.White=function(){return new n(1,1,1)},n.Purple=function(){return new n(.5,0,.5)},n.Magenta=function(){return new n(1,0,1)},n.Yellow=function(){return new n(1,1,0)},n.Gray=function(){return new n(.5,.5,.5)},n}();t.Color3=n;var r=function(){function t(t,i,n,r){this.r=t,this.g=i,this.b=n,this.a=r}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,n=255*this.g|0,r=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(n)+i.ToHex(r)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var n=parseInt(i.substring(1,3),16),r=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(n,r,o,e)},t.Lerp=function(i,n,r){var o=new t(0,0,0,0);return t.LerpToRef(i,n,r,o),o},t.LerpToRef=function(t,i,n,r){r.r=t.r+(i.r-t.r)*n,r.g=t.g+(i.g-t.g)*n,r.b=t.b+(i.b-t.b)*n,r.a=t.a+(i.a-t.a)*n},t.FromArray=function(i,n){return void 0===n&&(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.FromInts=function(i,n,r,o){return new t(i/255,n/255,r/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var n=[],r=0;r<t.length;r+=3){var o=r/3*4;n[o]=t[r],n[o+1]=t[r+1],n[o+2]=t[r+2],n[o+3]=1}return n}return t},t}();t.Color4=r;var o=function(){function n(t,i){this.x=t,this.y=i}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},n.prototype.getClassName=function(){return\"Vector2\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},n.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},n.prototype.addVector3=function(t){return new n(this.x+t.x,this.y+t.y)},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},n.prototype.multiplyByFloats=function(t,i){return new n(this.x*t,this.y*i)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},n.prototype.negate=function(){return new n((-this.x),(-this.y))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t)},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},n.prototype.clone=function(){return new n(this.x,this.y)},n.Zero=function(){return new n(0,0)},n.FromArray=function(t,i){return void 0===i&&(i=0),new n(t[i],t[i+1])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1]},n.CatmullRom=function(t,i,r,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h);return new n(a,u)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>r.y?r.y:e,e=e<i.y?i.y:e,new n(o,e)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y;return new n(c,p)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r;return new n(o,e)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y},n.Normalize=function(t){var i=t.clone();return i.normalize(),i},n.Minimize=function(t,i){var r=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new n(r,o)},n.Maximize=function(t,i){var r=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new n(r,o)},n.Transform=function(t,i){var r=n.Zero();return n.TransformToRef(t,i,r),r},n.TransformToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];n.x=r,n.y=o},n.PointInTriangle=function(t,i,n,r){var o=.5*(-n.y*r.x+i.y*(-n.x+r.x)+i.x*(n.y-r.y)+n.x*r.y),e=o<0?-1:1,s=(i.y*r.x-i.x*r.y+(r.y-i.y)*t.x+(i.x-r.x)*t.y)*e,h=(i.x*n.y-i.y*n.x+(i.y-n.y)*t.x+(n.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y;return n*n+r*r},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.DistanceOfPointFromSegment=function(t,i,r){var o=n.DistanceSquared(i,r);if(0===o)return n.Distance(t,i);var e=r.subtract(i),s=Math.max(0,Math.min(1,n.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return n.Distance(t,h)},n}();t.Vector2=o;var e=function(){function n(t,i,n){this.x=t,this.y=i,this.z=n}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},n.prototype.getClassName=function(){return\"Vector3\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},n.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),n=Math.sin(.5*(this.x+this.z)),r=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=r*s,t.y=-o*s,t.z=n*e,t.w=i*e,t},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},n.prototype.subtractFromFloats=function(t,i,r){return new n(this.x-t,this.y-i,this.z-r)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-n,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)},n.prototype.equalsToFloats=function(t,i,n){return this.x===t&&this.y===i&&this.z===n},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},n.prototype.multiplyByFloats=function(t,i,r){return new n(this.x*t,this.y*i,this.z*r)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},n.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},n.prototype.clone=function(){return new n(this.x,this.y,this.z)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},n.prototype.copyFromFloats=function(t,i,n){return this.x=t,this.y=i,this.z=n,this},n.GetClipFactor=function(t,i,r,o){var e=n.Dot(t,r)-o,s=n.Dot(i,r)-o,h=e/(e-s);return h},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromFloatArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2]},n.FromFloatsToRef=function(t,i,n,r){r.x=t,r.y=i,r.z=n},n.Zero=function(){return new n(0,0,0)},n.Up=function(){return new n(0,1,0)},n.TransformCoordinates=function(t,i){var r=n.Zero();return n.TransformCoordinatesToRef(t,i,r),r},n.TransformCoordinatesToRef=function(t,i,n){var r=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];n.x=r/s,n.y=o/s,n.z=e/s},n.TransformCoordinatesFromFloatsToRef=function(t,i,n,r,o){var e=t*r.m[0]+i*r.m[4]+n*r.m[8]+r.m[12],s=t*r.m[1]+i*r.m[5]+n*r.m[9]+r.m[13],h=t*r.m[2]+i*r.m[6]+n*r.m[10]+r.m[14],a=t*r.m[3]+i*r.m[7]+n*r.m[11]+r.m[15];o.x=e/a,o.y=s/a,o.z=h/a},n.TransformNormal=function(t,i){var r=n.Zero();return n.TransformNormalToRef(t,i,r),r},n.TransformNormalToRef=function(t,i,n){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,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+r.x)*e+(2*t.x-5*i.x+4*r.x-o.x)*s+(-t.x+3*i.x-3*r.x+o.x)*h),u=.5*(2*i.y+(-t.y+r.y)*e+(2*t.y-5*i.y+4*r.y-o.y)*s+(-t.y+3*i.y-3*r.y+o.y)*h),m=.5*(2*i.z+(-t.z+r.z)*e+(2*t.z-5*i.z+4*r.z-o.z)*s+(-t.z+3*i.z-3*r.z+o.z)*h);return new n(a,u,m)},n.Clamp=function(t,i,r){var o=t.x;o=o>r.x?r.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>r.y?r.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>r.z?r.z:s,s=s<i.z?i.z:s,new n(o,e,s)},n.Hermite=function(t,i,r,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+r.x*u+i.x*m+o.x*y,p=t.y*a+r.y*u+i.y*m+o.y*y,f=t.z*a+r.z*u+i.z*m+o.z*y;return new n(c,p,f)},n.Lerp=function(t,i,r){var o=t.x+(i.x-t.x)*r,e=t.y+(i.y-t.y)*r,s=t.z+(i.z-t.z)*r;return new n(o,e,s)},n.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},n.Cross=function(t,i){var r=n.Zero();return n.CrossToRef(t,i,r),r},n.CrossToRef=function(t,i,n){M.Vector3[0].x=t.y*i.z-t.z*i.y,M.Vector3[0].y=t.z*i.x-t.x*i.z,M.Vector3[0].z=t.x*i.y-t.y*i.x,n.copyFrom(M.Vector3[0])},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Project=function(t,i,r,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=n._viewportMatrixCache?n._viewportMatrixCache:n._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=n._matrixCache?n._matrixCache:n._matrixCache=new u;return i.multiplyToRef(r,y),y.multiplyToRef(m,y),n.TransformCoordinates(t,y)},n.UnprojectFromTransform=function(t,r,o,e,s){var h=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/r*2-1,t.y=-(t.y/o*2-1);var a=n.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},n.Unproject=function(t,r,o,e,s,h){var a=n._matrixCache?n._matrixCache:n._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new n(t.x/r*2-1,(-(t.y/o*2-1)),t.z),y=n.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z;return n*n+r*r+o*o},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n.RotationFromAxis=function(t,i,r){var o=n.Zero();return n.RotationFromAxisToRef(t,i,r,o),o},n.RotationFromAxisToRef=function(r,o,e,s){var h=r.normalize(),a=e.normalize(),u=p.X,m=p.Y,y=0,c=0,f=0,l=0,x=0,z=0,w=0,v=-1,d=0,g=M.Vector3[0],T=0,R=M.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?l=1:(w=a.z/a.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),R.x=l,R.y=x,R.z=z,R.normalize(),n.CrossToRef(h,R,g),g.normalize(),n.Dot(a,g)<0&&(v=1),T=n.Dot(h,R),T=Math.min(1,Math.max(-1,T)),f=Math.acos(T)*v,n.Dot(R,u)<0&&(f=Math.PI+f,R=R.scaleInPlace(-1),d++);var _=M.Vector3[2],b=M.Vector3[3];l=0,x=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?l=1:(w=R.z/R.x,l=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=l,_.y=x,_.z=z,_.normalize(),n.CrossToRef(_,R,b),b.normalize(),n.CrossToRef(a,_,g),g.normalize(),n.Dot(R,g)<0&&(v=1),T=n.Dot(a,_),T=Math.min(1,Math.max(-1,T)),c=Math.acos(T)*v,n.Dot(b,m)<0&&(c=Math.PI+c,d++),v=-1,n.CrossToRef(u,R,g),g.normalize(),n.Dot(g,m)<0&&(v=1),T=n.Dot(R,u),T=Math.min(1,Math.max(-1,T)),y=-Math.acos(T)*v,T<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=f},n}();t.Vector3=e;var s=function(){function n(t,i,n,r){this.x=t,this.y=i,this.z=n,this.w=r}return n.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},n.prototype.getClassName=function(){return\"Vector4\"},n.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},n.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},n.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},n.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},n.prototype.add=function(t){return new n(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},n.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},n.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},n.prototype.subtract=function(t){return new n(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},n.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},n.prototype.subtractFromFloats=function(t,i,r,o){return new n(this.x-t,this.y-i,this.z-r,this.w-o)},n.prototype.subtractFromFloatsToRef=function(t,i,n,r,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-n,o.w=this.w-r,this},n.prototype.negate=function(){return new n((-this.x),(-this.y),(-this.z),(-this.w))},n.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},n.prototype.scale=function(t){return new n(this.x*t,this.y*t,this.z*t,this.w*t)},n.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},n.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},n.prototype.equalsWithEpsilon=function(n,r){return void 0===r&&(r=t.Epsilon),n&&i.WithinEpsilon(this.x,n.x,r)&&i.WithinEpsilon(this.y,n.y,r)&&i.WithinEpsilon(this.z,n.z,r)&&i.WithinEpsilon(this.w,n.w,r)},n.prototype.equalsToFloats=function(t,i,n,r){return this.x===t&&this.y===i&&this.z===n&&this.w===r},n.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},n.prototype.multiply=function(t){return new n(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},n.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},n.prototype.multiplyByFloats=function(t,i,r,o){return new n(this.x*t,this.y*i,this.z*r,this.w*o)},n.prototype.divide=function(t){return new n(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},n.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},n.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},n.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},n.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},n.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},n.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},n.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},n.prototype.clone=function(){return new n(this.x,this.y,this.z,this.w)},n.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},n.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},n.FromArray=function(t,i){return i||(i=0),new n(t[i],t[i+1],t[i+2],t[i+3])},n.FromArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatArrayToRef=function(t,i,n){n.x=t[i],n.y=t[i+1],n.z=t[i+2],n.w=t[i+3]},n.FromFloatsToRef=function(t,i,n,r,o){o.x=t,o.y=i,o.z=n,o.w=r},n.Zero=function(){return new n(0,0,0,0)},n.Normalize=function(t){var i=n.Zero();return n.NormalizeToRef(t,i),i},n.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},n.Minimize=function(t,i){var n=t.clone();return n.MinimizeInPlace(i),n},n.Maximize=function(t,i){var n=t.clone();return n.MaximizeInPlace(i),n},n.Distance=function(t,i){return Math.sqrt(n.DistanceSquared(t,i))},n.DistanceSquared=function(t,i){var n=t.x-i.x,r=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return n*n+r*r+o*o+e*e},n.Center=function(t,i){var n=t.add(i);return n.scaleInPlace(.5),n},n}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,n){return new t(this.width*i,this.height*n)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var n=new t(this.width+i.width,this.height+i.height);return n},t.prototype.substract=function(i){var n=new t(this.width-i.width,this.height-i.height);return n},t.Lerp=function(i,n,r){var o=i.width+(n.width-i.width)*r,e=i.height+(n.height-i.height)*r;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,n,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===n&&(n=0),void 0===r&&(r=1),this.x=t,this.y=i,this.z=n,this.w=r}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,n,r){return this.x=t,this.y=i,this.z=n,this.w=r,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var n=new t(0,0,0,1);return this.multiplyToRef(i,n),n},t.prototype.multiplyToRef=function(t,i){var n=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,r=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(n,r,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var n,r,o,e=this.x,s=this.y,h=this.z,a=this.w;switch(i){case\"YZX\":var u=e*s+h*a;if(u>.499&&(n=2*Math.atan2(e,a),r=Math.PI/2,o=0),u<-.499&&(n=-2*Math.atan2(e,a),r=-Math.PI/2,o=0),isNaN(n)){var m=e*e,y=s*s,c=h*h;n=Math.atan2(2*s*a-2*e*h,1-2*y-2*c),r=Math.asin(2*u),o=Math.atan2(2*e*a-2*s*h,1-2*m-2*c)}break;default:throw new Error(\"Euler order \"+i+\" not supported yet.\")}return t.y=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,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(n+r),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(r+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(n+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var n=new t;return t.FromRotationMatrixToRef(i,n),n},t.FromRotationMatrixToRef=function(t,i){var n,r=t.m,o=r[0],e=r[4],s=r[8],h=r[1],a=r[5],u=r[9],m=r[2],y=r[6],c=r[10],p=o+a+c;p>0?(n=.5/Math.sqrt(p+1),i.w=.25/n,i.x=(y-u)*n,i.y=(s-m)*n,i.z=(h-e)*n):o>a&&o>c?(n=2*Math.sqrt(1+o-a-c),i.w=(y-u)/n,i.x=.25*n,i.y=(e+h)/n,i.z=(s+m)/n):a>c?(n=2*Math.sqrt(1+a-o-c),i.w=(s-m)/n,i.x=(e+h)/n,i.y=.25*n,i.z=(u+y)/n):(n=2*Math.sqrt(1+c-o-a),i.w=(h-e)/n,i.x=(s+m)/n,i.y=(u+y)/n,i.z=.25*n)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,n){return t.RotationAxisToRef(i,n,new t)},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(i/2);return t.normalize(),n.w=Math.cos(i/2),n.x=t.x*r,n.y=t.y*r,n.z=t.z*r,n},t.FromArray=function(i,n){return n||(n=0),new t(i[n],i[n+1],i[n+2],i[n+3])},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){var o=.5*n,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);r.x=c*u*a+y*m*h,r.y=y*m*a-c*u*h,r.z=c*m*h-y*u*a,r.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,n,r){var o=new t;return t.RotationAlphaBetaGammaToRef(i,n,r,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,n,r){var o=.5*(n+t),e=.5*(n-t),s=.5*i;r.x=Math.cos(e)*Math.sin(s),r.y=Math.sin(e)*Math.sin(s),r.z=Math.sin(o)*Math.cos(s),r.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,n,r){var o,e,s=r,h=i.x*n.x+i.y*n.y+i.z*n.z+i.w*n.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}return new t(e*i.x+o*n.x,e*i.y+o*n.y,e*i.z+o*n.z,e*i.w+o*n.w)},t}();t.Quaternion=a;var u=function(){function t(){this.m=new Float32Array(16)}return t.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},t.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],n=this.m[9]*this.m[14]-this.m[10]*this.m[13],r=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*n)-this.m[1]*(this.m[4]*t-this.m[6]*r+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*r+this.m[7]*e)-this.m[3]*(this.m[4]*n-this.m[5]*o+this.m[6]*e)},t.prototype.toArray=function(){return this.m},t.prototype.asArray=function(){return this.toArray()},t.prototype.invert=function(){return this.invertToRef(this),this},t.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},t.prototype.add=function(i){var n=new t;return this.addToRef(i,n),n},t.prototype.addToRef=function(t,i){for(var n=0;n<16;n++)i.m[n]=this.m[n]+t.m[n];return this},t.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},t.prototype.invertToRef=function(t){var i=this.m[0],n=this.m[1],r=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],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=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*T,b=-(e*v-s*g+h*T),F=1/(i*R+n*_+r*M+o*b),A=h*x-a*l,L=s*x-a*f,C=s*l-h*f,P=e*x-a*p,Z=e*l-h*p,S=e*f-s*p,I=h*c-a*y,D=s*c-a*m,q=s*y-h*m,V=e*c-a*u,H=e*y-h*u,N=e*m-s*u;return t.m[0]=R*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=b*F,t.m[1]=-(n*z-r*w+o*v)*F,t.m[5]=(i*z-r*d+o*g)*F,t.m[9]=-(i*w-n*d+o*T)*F,t.m[13]=(i*v-n*g+r*T)*F,t.m[2]=(n*A-r*L+o*C)*F,t.m[6]=-(i*A-r*P+o*Z)*F,t.m[10]=(i*L-n*P+o*S)*F,t.m[14]=-(i*C-n*Z+r*S)*F,t.m[3]=-(n*I-r*D+o*q)*F,t.m[7]=(i*I-r*V+o*H)*F,t.m[11]=-(i*D-n*V+o*N)*F,t.m[15]=(i*q-n*H+r*N)*F,this},t.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},t.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},t.prototype.multiply=function(i){var n=new t;return this.multiplyToRef(i,n),n},t.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},t.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var n=0;n<16;n++)t[i+n]=this.m[n];return this},t.prototype.multiplyToRef=function(t,i){\nreturn this.multiplyToArray(t,i.m,0),this},t.prototype.multiplyToArray=function(t,i,n){var r=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],l=this.m[12],x=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],T=t.m[3],R=t.m[4],_=t.m[5],M=t.m[6],b=t.m[7],F=t.m[8],A=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[n]=r*v+o*R+e*F+s*P,i[n+1]=r*d+o*_+e*A+s*Z,i[n+2]=r*g+o*M+e*L+s*S,i[n+3]=r*T+o*b+e*C+s*I,i[n+4]=h*v+a*R+u*F+m*P,i[n+5]=h*d+a*_+u*A+m*Z,i[n+6]=h*g+a*M+u*L+m*S,i[n+7]=h*T+a*b+u*C+m*I,i[n+8]=y*v+c*R+p*F+f*P,i[n+9]=y*d+c*_+p*A+f*Z,i[n+10]=y*g+c*M+p*L+f*S,i[n+11]=y*T+c*b+p*C+f*I,i[n+12]=l*v+x*R+z*F+w*P,i[n+13]=l*d+x*_+z*A+w*Z,i[n+14]=l*g+x*M+z*L+w*S,i[n+15]=l*T+x*b+z*C+w*I,this},t.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},t.prototype.clone=function(){return t.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},t.prototype.getClassName=function(){return\"Matrix\"},t.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},t.prototype.decompose=function(n,r,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(n.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),n.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),n.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===n.x||0===n.y||0===n.z)return r.x=0,r.y=0,r.z=0,r.w=1,!1;var u=t.FromValues(this.m[0]/n.x,this.m[1]/n.x,this.m[2]/n.x,0,this.m[4]/n.y,this.m[5]/n.y,this.m[6]/n.y,0,this.m[8]/n.z,this.m[9]/n.z,this.m[10]/n.z,0,0,0,0,1);return a.FromRotationMatrixToRef(u,r),!0},t.FromArray=function(i,n){var r=new t;return n||(n=0),t.FromArrayToRef(i,n,r),r},t.FromArrayToRef=function(t,i,n){for(var r=0;r<16;r++)n.m[r]=t[r+i]},t.FromFloat32ArrayToRefScaled=function(t,i,n,r){for(var o=0;o<16;o++)r.m[o]=t[o+i]*n},t.FromValuesToRef=function(t,i,n,r,o,e,s,h,a,u,m,y,c,p,f,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]=e,x.m[6]=s,x.m[7]=h,x.m[8]=a,x.m[9]=u,x.m[10]=m,x.m[11]=y,x.m[12]=c,x.m[13]=p,x.m[14]=f,x.m[15]=l},t.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},t.prototype.setRow=function(t,i){if(t<0||t>3)return this;var n=4*t;return this.m[n+0]=i.x,this.m[n+1]=i.y,this.m[n+2]=i.z,this.m[n+3]=i.w,this},t.FromValues=function(i,n,r,o,e,s,h,a,u,m,y,c,p,f,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]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=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),e=t.Identity();return n.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(r),o},t.Identity=function(){return t.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},t.IdentityToRef=function(i){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,i)},t.Zero=function(){return t.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},t.RotationX=function(i){var n=new t;return t.RotationXToRef(i,n),n},t.Invert=function(i){var n=new t;return i.invertToRef(n),n},t.RotationXToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=r,i.m[10]=r,i.m[9]=-n,i.m[6]=n,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationY=function(i){var n=new t;return t.RotationYToRef(i,n),n},t.RotationYToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=r,i.m[2]=-n,i.m[8]=n,i.m[10]=r,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationZ=function(i){var n=new t;return t.RotationZToRef(i,n),n},t.RotationZToRef=function(t,i){var n=Math.sin(t),r=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=r,i.m[1]=n,i.m[4]=-n,i.m[5]=r,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},t.RotationAxis=function(i,n){var r=t.Zero();return t.RotationAxisToRef(i,n,r),r},t.RotationAxisToRef=function(t,i,n){var r=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),n.m[0]=t.x*t.x*e+o,n.m[1]=t.x*t.y*e-t.z*r,n.m[2]=t.x*t.z*e+t.y*r,n.m[3]=0,n.m[4]=t.y*t.x*e+t.z*r,n.m[5]=t.y*t.y*e+o,n.m[6]=t.y*t.z*e-t.x*r,n.m[7]=0,n.m[8]=t.z*t.x*e-t.y*r,n.m[9]=t.z*t.y*e+t.x*r,n.m[10]=t.z*t.z*e+o,n.m[11]=0,n.m[15]=1},t.RotationYawPitchRoll=function(i,n,r){var o=new t;return t.RotationYawPitchRollToRef(i,n,r,o),o},t.RotationYawPitchRollToRef=function(t,i,n,r){a.RotationYawPitchRollToRef(t,i,n,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(r)},t.Scaling=function(i,n,r){var o=t.Zero();return t.ScalingToRef(i,n,r,o),o},t.ScalingToRef=function(t,i,n,r){r.m[0]=t,r.m[1]=0,r.m[2]=0,r.m[3]=0,r.m[4]=0,r.m[5]=i,r.m[6]=0,r.m[7]=0,r.m[8]=0,r.m[9]=0,r.m[10]=n,r.m[11]=0,r.m[12]=0,r.m[13]=0,r.m[14]=0,r.m[15]=1},t.Translation=function(i,n,r){var o=t.Identity();return t.TranslationToRef(i,n,r,o),o},t.TranslationToRef=function(i,n,r,o){t.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,i,n,r,1,o)},t.Lerp=function(i,n,r){for(var o=t.Zero(),e=0;e<16;e++)o.m[e]=i.m[e]*(1-r)+n.m[e]*r;return o},t.DecomposeLerp=function(i,n,r){var o=new e(0,0,0),s=new a,h=new e(0,0,0);i.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);n.decompose(u,m,y);var c=e.Lerp(o,u,r),p=a.Slerp(s,m,r),f=e.Lerp(h,y,r);return t.Compose(c,p,f)},t.LookAtLH=function(i,n,r){var o=t.Zero();return t.LookAtLHToRef(i,n,r,o),o},t.LookAtLHToRef=function(i,n,r,o){n.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(r,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,i),h=-e.Dot(this._yAxis,i),a=-e.Dot(this._zAxis,i);return t.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},t.OrthoLH=function(i,n,r,o){var e=t.Zero();return t.OrthoLHToRef(i,n,r,o,e),e},t.OrthoLHToRef=function(i,n,r,o,e){var s=2/i,h=2/n,a=1/(o-r),u=r/(r-o);t.FromValuesToRef(s,0,0,0,0,h,0,0,0,0,a,0,0,0,u,1,e)},t.OrthoOffCenterLH=function(i,n,r,o,e,s){var h=t.Zero();return t.OrthoOffCenterLHToRef(i,n,r,o,e,s,h),h},t.OrthoOffCenterLHToRef=function(t,i,n,r,o,e,s){s.m[0]=2/(i-t),s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2/(r-n),s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-1/(o-e),s.m[8]=s.m[9]=s.m[11]=0,s.m[12]=(t+i)/(t-i),s.m[13]=(r+n)/(n-r),s.m[14]=o/(o-e),s.m[15]=1},t.PerspectiveLH=function(i,n,r,o){var e=t.Zero();return e.m[0]=2*r/i,e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2*r/n,e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-o/(r-o),e.m[8]=e.m[9]=0,e.m[11]=1,e.m[12]=e.m[13]=e.m[15]=0,e.m[14]=r*o/(r-o),e},t.PerspectiveFovLH=function(i,n,r,o){var e=t.Zero();return t.PerspectiveFovLHToRef(i,n,r,o,e),e},t.PerspectiveFovLHToRef=function(t,i,n,r,o,e){void 0===e&&(e=!0);var s=1/Math.tan(.5*t);e?o.m[0]=s/i:o.m[0]=s,o.m[1]=o.m[2]=o.m[3]=0,e?o.m[5]=s:o.m[5]=s*i,o.m[4]=o.m[6]=o.m[7]=0,o.m[8]=o.m[9]=0,o.m[10]=-r/(n-r),o.m[11]=1,o.m[12]=o.m[13]=o.m[15]=0,o.m[14]=n*r/(n-r)},t.PerspectiveFovWebVRToRef=function(t,i,n,r,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);r.m[0]=u,r.m[1]=r.m[2]=r.m[3]=r.m[4]=0,r.m[5]=m,r.m[6]=r.m[7]=0,r.m[8]=(h-a)*u*.5,r.m[9]=-((e-s)*m*.5),r.m[10]=-n/(i-n),r.m[11]=1,r.m[12]=r.m[13]=r.m[15]=0,r.m[14]=i*n/(i-n)},t.GetFinalMatrix=function(i,n,r,o,e,s){var h=i.width,a=i.height,u=i.x,m=i.y,y=t.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return n.multiply(r).multiply(o).multiply(y)},t.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},t.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},t.Transpose=function(i){var n=new t;return n.m[0]=i.m[0],n.m[1]=i.m[4],n.m[2]=i.m[8],n.m[3]=i.m[12],n.m[4]=i.m[1],n.m[5]=i.m[5],n.m[6]=i.m[9],n.m[7]=i.m[13],n.m[8]=i.m[2],n.m[9]=i.m[6],n.m[10]=i.m[10],n.m[11]=i.m[14],n.m[12]=i.m[3],n.m[13]=i.m[7],n.m[14]=i.m[11],n.m[15]=i.m[15],n},t.Reflection=function(i){var n=new t;return t.ReflectionToRef(i,n),n},t.ReflectionToRef=function(t,i){t.normalize();var n=t.normal.x,r=t.normal.y,o=t.normal.z,e=-2*n,s=-2*r,h=-2*o;i.m[0]=e*n+1,i.m[1]=s*n,i.m[2]=h*n,i.m[3]=0,i.m[4]=e*r,i.m[5]=s*r+1,i.m[6]=h*r,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},t._tempQuaternion=new a,t._xAxis=e.Zero(),t._yAxis=e.Zero(),t._zAxis=e.Zero(),t}();t.Matrix=u;var m=function(){function t(t,i,n,r){this.normal=new e(t,i,n),this.d=r}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var n=u.Transpose(i),r=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=r*n.m[0]+o*n.m[1]+e*n.m[2]+s*n.m[3],a=r*n.m[4]+o*n.m[5]+e*n.m[6]+s*n.m[7],m=r*n.m[8]+o*n.m[9]+e*n.m[10]+s*n.m[11],y=r*n.m[12]+o*n.m[13]+e*n.m[14]+s*n.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,n){var r,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=n.x-t.x,a=n.y-t.y,u=n.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return r=0!==p?1/p:0,this.normal.x=m*r,this.normal.y=y*r,this.normal.z=c*r,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var n=e.Dot(this.normal,t);return n<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,n,r){var o=new t(0,0,0,0);return o.copyFromPoints(i,n,r),o},t.FromPositionAndNormal=function(i,n){var r=new t(0,0,0,0);return n.normalize(),r.normal=n,r.d=-(n.x*i.x+n.y*i.y+n.z*i.z),r},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,n){var r=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(n,i)+r},t}();t.Plane=m;var y=function(){function t(t,i,n,r){this.x=t,this.y=i,this.width=n,this.height=r}return t.prototype.toGlobal=function(i,n){return new t(this.x*i,this.y*n,this.width*i,this.height*n)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var n=[],r=0;r<6;r++)n.push(new m(0,0,0,0));return t.GetPlanesToRef(i,n),n},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var p=(t.Space,function(){function t(){}return t.X=new e(1,0,0),t.Y=new e(0,1,0),t.Z=new e(0,0,1),t}());t.Axis=p;var f=function(){function t(){}return t.interpolate=function(t,i,n,r,o){for(var e=1-3*r+3*i,s=3*r-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*n+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=f,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var l=t.Orientation,x=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,n){var r=n.subtract(i),o=Math.atan2(r.y,r.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=x;var z=function(){function t(t,i,n){this.startPoint=t,this.midPoint=i,this.endPoint=n;var r=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,s=(r-Math.pow(n.x,2)-Math.pow(n.y,2))/2,h=(t.x-i.x)*(i.y-n.y)-(i.x-n.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-n.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-n.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=x.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=x.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=x.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?l.CW:l.CCW,this.angle=x.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=z;var w=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var n=new o(t,i),r=this._points[this._points.length-1];return this._points.push(n),this._length+=n.subtract(r).length(),this},t.prototype.addArcTo=function(t,i,n,r,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(n,r),u=new z(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],n=this._points[0];t+=n.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),n=0,r=0;r<this._points.length;r++){var e=(r+1)%this._points.length,s=this._points[r],h=this._points[e],a=h.subtract(s),u=a.length()+n;if(i>=n&&i<=u){var m=a.normalize(),y=i-n;return new o(s.x+m.x*y,s.y+m.y*y)}n=u}return o.Zero()},t.StartingAt=function(i,n){return new t(i,n)},t}();t.Path2=w;var v=function(){function n(t,i,n){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var r=0;r<t.length;r++)this._curve[r]=t[r].clone();this._raw=n||!1,this._compute(i)}return n.prototype.getCurve=function(){return this._curve},n.prototype.getTangents=function(){return this._tangents},n.prototype.getNormals=function(){return this._normals},n.prototype.getBinormals=function(){return this._binormals},n.prototype.getDistances=function(){return this._distances},n.prototype.update=function(t,i){for(var n=0;n<t.length;n++)this._curve[n].x=t[n].x,this._curve[n].y=t[n].y,this._curve[n].z=t[n].z;return this._compute(i),this},n.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var n=this._tangents[0],r=this._normalVector(this._curve[0],n,t);this._normals[0]=r,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(n,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},n.prototype._getFirstNonNullVector=function(t){for(var i=1,n=this._curve[t+i].subtract(this._curve[t]);0===n.length()&&t+i+1<this._curve.length;)i++,n=this._curve[t+i].subtract(this._curve[t]);return n},n.prototype._getLastNonNullVector=function(t){for(var i=1,n=this._curve[t].subtract(this._curve[t-i]);0===n.length()&&t>i+1;)i++,n=this._curve[t].subtract(this._curve[t-i]);return n},n.prototype._normalVector=function(n,r,o){var s,h=r.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(r.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(r.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(r,a)}else s=e.Cross(r,o),e.CrossToRef(s,r,s);return s.normalize(),s},n}();t.Path3D=v;var d=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,n,r,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,n,r){var o=(1-t)*(1-t)*i+2*t*(1-t)*n+t*t*r;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,n.x,r.x),h(a/o,i.y,n.y,r.y),h(a/o,i.z,n.z,r.z)));return new t(s)},t.CreateCubicBezier=function(i,n,r,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,n,r,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*n+3*t*t*(1-t)*r+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,n.x,r.x,o.x),a(u/s,i.y,n.y,r.y,o.y),a(u/s,i.z,n.z,r.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,n,r,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,n,r,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var n=this._points[this._points.length-1],r=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)r.push(o[e].subtract(o[0]).add(n));var s=new t(r);return s},t.prototype._computeLength=function(t){for(var i=0,n=1;n<t.length;n++)i+=t[n].subtract(t[n-1]).length();return i},t}();t.Curve3=d;var g=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,n){var r=new e(i.r,i.g,i.b),o=r.scale(n);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=g;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var n=new t;return n.x=i.L11.scale(1.02333),n.y=i.L1_1.scale(1.02333),n.z=i.L10.scale(1.02333),n.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),n.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),n.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),n.yz=i.L2_1.scale(.858086),n.zx=i.L21.scale(.858086),n.xy=i.L2_2.scale(.858086),n},t}();t.SphericalPolynomial=T;var R=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=R;var _=function(){function t(t,i,n){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===n&&(n=o.Zero()),this.position=t,this.normal=i,this.uv=n}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=_;var M=function(){function t(){}return t.Color3=[n.Black(),n.Black(),n.Black()],t.Vector2=[o.Zero(),o.Zero(),o.Zero()],t.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],t.Vector4=[s.Zero(),s.Zero(),s.Zero()],t.Quaternion=[new a(0,0,0,0)],t.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t}();t.Tmp=M}(BABYLON||(BABYLON={}));";
  62034. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  62035. module.exports = BABYLON;
  62036. };